Box<T>
The generic type Box in the standard library gives us the simplest way to allocate values in the heap. It's simply declared as a tuple struct in the standard library, and wraps any type given to it and puts it on heap. If you're familiar with the concept of boxing and unboxing from other languages, such as Java where you have Boxed integers as the Integer class, this provides a similar abstraction. The ownership semantics with Box type depends on the wrapped type. If the underlying type is Copy, the Box instance becomes copy, otherwise it moves by default.
To create a heap allocated value of type T using a Box, we simply call the associated new method, passing in the value. Creating the Box value wrapping a type T gives back the
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access