Rust Box

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.

Links to this page
  • Rust Trait

    One could use #202206221113 as in Box<dyn Trait> in order to have a container that could include various types that share the same trait. For example:

  • Rust Smart Pointers
  • Rust RefCell

    RefCell<T> (import it from std::cell::RefCell) is a kind of #202111301656 that implements single ownership but allows interior mutability which permits the mutation of data on immutable references. Unlike 202206221113 and 202206221720, it checks the 202206241126# in runtime rather in compile time. This means that instead of showing up as a compilation error, the program will still be able to be compiled but panic and exit if there is a violation of the borrowing rule.

#rust #memory #resource