As others pointed out, currently, an enum type always has a fixed size, and if a fixed size is assumed the recursive enum type cannot exist.
To allow such a recursive enum type, two features are necessary.
Allow dynamically sized enum type
Like dynamically sized structs, an enum type can automatically make dynamically sized if one of the variants has a dynamically sized field at the end.
I found an old RFC issue https://github.com/rust-lang/rfcs/issues/1151. There are some subtleties regarding where to put enum tag, as the tag is necessary as the metadata.
Automatically make otherwise infinitely sized enum types to dynamically sized
If DST enum is implemented, it is possible to make recursive enum "just work" by making it dynamically sized automatically.
However, I think automatic dynamically sizing is problematic when multiple types are mutually recursive, as there are multiple ways to "solve" the infinite-ness. Consider these mutually recursive enum types:
enum E1 {
X,
Y(E2),
}
enum E2 {
X,
Y(E1),
}
Currently, there are two minimal ways to make it work by boxing: either modifying E1
to have X(Box<E2>)
, or modifying E2
to have Y(Box<E1>)
. Respectively, either E1
or E2
, or both can be made dynamically sized, but the compiler has to determine which way is preferred.
I guess there are more issues when generics are involved.
Thus, I think, requiring an explicit keyword or something is a sensible way to support the recursive dynamically sized types.