Javatpoint Logo
Javatpoint Logo

Box<T>

  • Box<T> is a smart pointer that points to the data which is allocated on the heap of type T. Box<T> allow you to store the data on the heap rather than the stack.
  • Box<T> is an owned pointer.
  • Boxes do not have a performance overhead, other than storing the data on the heap.
  • When the Box goes out of the scope, then the destructor is called to destroy all the inner objects and release the memory.

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:

Output:

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:

Rust Box

Cons List

  • Cons stand for "Construct function".
  • Cons list is a data structure which is used to construct a new pair from the two arguments, and this pair is known as a List.
  • Suppose we have two elements x and y, then the cons function cons the "x onto y" means that we construct the new container by putting the element x first , and then followed by the element y.
  • Cons list contains two elements, i.e., the current item and the last item. The last item of the cons list is Nil as Nil does not contain the next item.

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:

Output:

Rust Box

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.


Rust Box

Let's see a simple example:

Output:

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




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials