enum List {
Cons(i32, List),
Nil,
}
fn main() {
let _l = List::Nil;
}What does
rustc (edition 2021) do with this program?- aIt compiles;
List::Niloccupies 0 bytes so no heap allocation is needed for the empty list - b
E0072:Listhas infinite size; the variant needs an indirection such asBox<List>✓ - cIt compiles, but constructing any
Consnode at runtime overflows the stack and panics - dIt fails with
E0382since the innerListis moved intoConswhile still being defined
Explanation:An enum must have a known, finite size at compile time.
Cons(i32, List) stores a List inline, so the size of List would depend on itself. The compiler rejects this with E0072 (measured on rustc 1.98). Putting the recursive part behind a pointer (Cons(i32, Box<List>)) gives the variant a fixed 8-byte field, and the whole enum then measures 16 bytes on a 64-bit target. There is no runtime stage here at all: the program never gets past type checking.