2022-12-21 16:36:30 +01:00
# Box with Recursive Data Structures
Recursive data types or data types with dynamic sizes need to use a `Box` :
```rust,editable
#[derive(Debug)]
enum List< T > {
Cons(T, Box< List < T > >),
Nil,
}
fn main() {
let list: List< i32 > = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
println!("{list:?}");
}
```
```bob
Stack Heap
.- - - - - - - - - - - - -. .- - - - - - - - - - - - - - - - - - - - - - - -.
: : : :
: list : : :
2023-02-14 19:03:46 +00:00
: +------+----+----+ : : +------+----+----+ +------+----+----+ :
: | Cons | 1 | o--+----+-----+--->| Cons | 2 | o--+--->| Nil | // | // | :
: +------+----+----+ : : +------+----+----+ +------+----+----+ :
2022-12-21 16:36:30 +01:00
: : : :
: : : :
2023-02-14 19:03:46 +00:00
'- - - - - - - - - - - - -' '- - - - - - - - - - - - - - - - - - - - - - - -'
2022-12-21 16:36:30 +01:00
```
2023-01-23 12:54:06 +00:00
< details >
2023-02-14 19:03:46 +00:00
2023-02-09 12:49:00 -08:00
* If the `Box` was not used here and we attempted to embed a `List` directly into the `List` ,
2023-01-23 12:54:06 +00:00
the compiler would not compute a fixed size of the struct in memory, it would look infinite.
2023-02-14 19:03:46 +00:00
2023-02-09 12:49:00 -08:00
* `Box` solves this problem as it has the same size as a regular pointer and just points at the next
2023-02-14 19:03:46 +00:00
element of the `List` in the heap.
2023-02-14 12:22:49 -08:00
* Remove the `Box` in 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.
2023-01-23 12:54:06 +00:00
< / details >