Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Smart Pointers and Memory

Rust Box<T> type

Reference for Rust Box<T>: heap allocation, recursive types, Box<dyn Trait> trait objects, moving out of a box, into_raw, leak and Deref behavior.

Box<T> is the simplest smart pointer: it owns a value of type T stored on the heap. The box itself is one pointer wide (two for unsized T) and lives wherever you put it, usually the stack. When the box goes out of scope, it drops the value and frees the allocation. There is no reference counting and no runtime overhead beyond the allocation.

You reach for Box in three situations: a type whose size is not known at compile time, such as a recursive enum List { Cons(i32, Box<List>), Nil }; moving a large value around cheaply (only the pointer moves); and owning a trait object, Box<dyn Trait>, for dynamic dispatch.

Rust
let b = Box::new(5);
let sum = *b + 1;          // deref to read the value
let shape: Box<dyn std::fmt::Debug> = Box::new("hi");

Try it

Rust Recursive types and boxed values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Trait objects and Drop order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
pub struct Box<T: ?Sized, A: Allocator = Global>(/* private */);

impl<T> Box<T> {
    pub fn new(x: T) -> Box<T>;
    pub fn pin(x: T) -> Pin<Box<T>>;
}
impl<T: ?Sized> Box<T> {
    pub fn into_raw(b: Box<T>) -> *mut T;       // unsafe to turn back:
    pub unsafe fn from_raw(raw: *mut T) -> Box<T>;
    pub fn leak<'a>(b: Box<T>) -> &'a mut T;
    pub fn into_inner(boxed: Box<T>) -> T where T: Sized; // unstable; use *boxed
}
// Deref/DerefMut to T, Drop, Clone (T: Clone), From<T>, Default (T: Default)
Name Description
x The value to move onto the heap.
b The box being consumed. Box methods are associated functions (Box::leak(b)), not methods, to avoid clashing with methods of T.
raw A pointer previously produced by Box::into_raw with the same allocator and type.

Returns: new returns the owning box. leak returns a reference that lives for any chosen lifetime and is never freed.

Errors and panics: Box::new aborts on allocation failure (it does not return an error). from_raw is unsafe: passing a pointer not from into_raw, or calling it twice, is undefined behavior (double free).

Usage notes

  • Deref coercion: &Box<T> coerces to &T, so you can pass a &Box<String> where &str is expected.
  • Moving out: *boxed moves the value out and consumes the box. This is allowed only for Box, not for other pointers.
  • Trait objects: Box<dyn Trait> is a fat pointer (data pointer + vtable); methods are dispatched through the vtable. A dyn Trait also has + Send + Sync and lifetime variants such as Box<dyn Fn() + Send + 'static>.
  • Zero-sized values allocate nothing: Box::new(()) does not touch the heap.
  • Option niche: Option<Box<T>> is the same size as Box<T> because null is used for None; that makes it the standard "nullable owned pointer".
  • Not for speed by default. Small values are faster on the stack. Allocation costs more than the copy of a few words.
  • Large arrays: Box::new([0u8; 1_000_000]) may build the array on the stack first in debug builds; vec![0; n].into_boxed_slice() avoids that.
  • Cloning a box deep-clones its content, and Box<dyn Trait> is not Clone unless you add a clone_box method yourself.