Box with Recursive Data Structures
Recursive data types or data types with dynamic sizes need to use a Box:
1. #[derive(Debug)]
2. enum List<T> {
3. Cons(T, Box<List<T>>),
4. Nil,
5. }
7. fn main() {
8. let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
9. println!("{list:?}");
10. }

- If the
Boxwas not used here and we attempted to embed aListdirectly into theList, the compiler would not compute a fixed size of the struct in memory, it would look infinite. Boxsolves this problem as it has the same size as a regular pointer and just points at the next element of theListin the heap.- Remove the
Boxin the List definition and show the compiler error. “Recursive with indirection” is a hint you might want to use a Box or reference of some kind, instead of storing a value directly.
