Box<T>
is a kind of #202111301656 implemented by Rust standard library which is actually a single element Tuple with 202206221604# and Drop 202204061235#. It doesn’t have performance overhead. It stores data on the 202202062259# rather than on the 202112031157#. We can directly print the value (if it is of simple type) just like other primitive types without dereferencing it. Comparing to normal references, box is pointing to a copied value.
Boxes are often used to accommodate the following situations:
- The size of the type can’t be known at compile time (recursive type) but at the same time it is required to have an exact size when used.
- Ensure that the ownership transfer doesn’t result in an expensive copy especially if the data is large.
- To have a type that implements a particular trait# rather than a specific type.
For example, we can define a 202110191710# as a recursive type using the Box:
enum List {
Cons(i32, Box<List>),
Nil,
}
If the above doesn’t utilise the Box, the Rust compiler will complain about that it doesn’t know the exact size of the data structure. It does suggest us to make use of indirection, by changing the data structure to store the value indirectly by storing a pointer to the value instead of storing a value directly.