Using Box<T> to store the data on the heap.
Mainly, Box<T> is used to store the data on the heap. Let's understand this through a simple example:
value of a is : 1
In the above example, a contains the value of Box that points to the data 1. If we access the value of Box, then the program prints '1'. When the program ends, then the Box is deallocated. The box is stored on the stack, and the data that it points to is stored on the heap.
Let's see the diagrammatic representation of the above example:
Now, we create the enum that contains the cons list.
In the above code, we create the enum of List type which contains the cons list data structure of i32 values.
Now, we use the above List type in the following example:
In the above example, the Rust compiler throws an error "has infinite size" as List type contains the variant which is recursive. As a result, Rust is not able to find out how much space is required to store the List value. The problem of an infinite size can be overcome by using the Box<T>.
Using Box<T> to get the size of a recursive type
Rust cannot figure out how much space is required to store the recursive data types. The Rust compiler shows the error in the previous case:
In the above case, we can use the Box<T> pointer as the compiler knows how much space Box<T> pointer requires. The size of Box<T> pointer will not change during the execution of a program. The Box<T> pointer points to the List value that will be stored on the heap rather than in the cons variant. The Box<T> pointer can be placed directly in the cons variant.
Let's see a simple example:
Cons(1, Cons(2, Cons(3, Nil)))
Note: If we use the Box<T> pointer in recursive data types, then the size of the List value will be equal to the size of i32 value plus the size of the box pointer?s data.
Next TopicDeref Trait