Back to questions
JuniorTheoryCommon
What happens when this program is built and run?
enum List {
Cons(i32, List),
Nil,
}
fn main() {
let list = List::Cons(1, List::Cons(2, List::Nil));
match list {
List::Cons(n, _) => println!("{n}"),
List::Nil => println!("0"),
}
}It does not compile
- Expecting
1becauseNilends the list: the compiler sizes the type, not the value, and aListstored inline inConsmakes the type infinite (E0072). - Expecting a panic at run time: the size of every type is fixed at compile time, so the error comes from the compiler and the program never starts.
- How would you change the
Consvariant so that the program compiles and prints1? - Why does a
Box<List>field give theListtype a size the compiler knows?