Anonymous enums would be so good

78 points zannabianca1997

One of the best features of Rust is the algebraic type system, of which the most outstanding feature is the enum not as a restricted integer but as a sum type. But there is more: enum variants can be effectively treated as anonymous structs, refactoring what would be something like this:

struct A;
struct B(usize, usize);
struct C {
  foo: isize,
  bar: String,
}

enum Composed {
  A(A),
  B(B),
  C(C),
}

in this beauty:

enum Composed {
  A,
  B(usize, usize),
  C{
    foo: isize,
    bar: String,
  },
}

This makes writing types containing multiple possible values easy, the best of the strongly typed languages I tried. And if you find the need to separate a variant, the first option is always available.

Lately, I struggle with the opposite problem: types containing some common data. The pattern I find myself writing often is:

struct Foo {
  common: T // Some common data...
  content: FooContent
}
enum FooContent {
  // alternative data
}

The problem I have with this is that FooContent is often pure boilerplate. Really rarely do you manipulate it outside of Foo, and in a lot of libraries you can find the same pattern. The only alternative I found is to rewrite common to be part of every variant but is verbose and needs a lot of boilerplate for extraction. So, why can't we have:

struct Foo {
  common: T // Some common data...
  content: enum {
    // alternative data
  }
}

It's the part I miss about C anonymous unions and struct, and it would make for great type definitions (Error types in particular). It just seems the natural counterpart of enum struct variants. The only problems I see are how to type Foo.content and references to it, and how to match against it. For the first one, I would say that anonymous types exist (see closures) while for the second there is the need for some new syntax, something like Foo { common: _, contend: ContentVariant }.

Am I missing something subtle (or obvious) that makes this more difficult than it seems? Or there is some alternative type of definition that makes it unnecessary?