← Back to Rust Course | Chapter 13: Smart Pointers & Unsafe | Lesson 1 of 7

The Box Type

Box puts a value on the heap and gives you a simple handle to it, which is handy for big or self-referencing data.

Boxing a Value

Box::new(value) moves a value onto the heap and returns a Box<T> pointing to it. The Box itself lives on the stack and owns the heap data.

Example: Boxing a Value

markup
fn main() {
    let boxed_number = Box::new(42);
    println!("Boxed value: {}", boxed_number);
}

Boxing a Recursive Type

Recursive types, like a simple linked list, would have an infinite size without indirection. Wrapping the recursive field in Box gives it a fixed, known size, since a Box is just a pointer.

Example: Boxing a Recursive Type

markup
enum List {
    Cons(i32, Box<List>),
    Nil,
}

use List::{Cons, Nil};

fn main() {
    let list = Cons(1, Box::new(Cons(2, Box::new(Nil))));
    if let Cons(value, _) = list {
        println!("First value: {}", value);
    }
}

Dereferencing a Box

The * operator dereferences a Box, giving direct access to the value it contains, just like dereferencing any other pointer-like type.

Example: Dereferencing a Box

markup
fn main() {
    let boxed = Box::new(10);
    let doubled = *boxed * 2;
    println!("Doubled: {}", doubled);
}

Box for Trait Objects

Box<dyn Trait> is a common way to store a value whose exact concrete type is not known at compile time, as long as it implements a specific trait.

Example: Box for Trait Objects

markup
trait Speak {
    fn say(&self) -> String;
}

struct Dog;

impl Speak for Dog {
    fn say(&self) -> String {
        String::from("Woof!")
    }
}

fn main() {
    let animal: Box<dyn Speak> = Box::new(Dog);
    println!("{}", animal.say());
}
Common Mistakes
  1. Using Box<T> when a value would fit perfectly fine on the stack, adding unnecessary heap allocation overhead.
  2. Forgetting a recursive data type (like a linked list node) needs Box (or similar) to have a known, finite size.
  3. Assuming Box allows shared ownership -- it is single-owner, just like any other owned value; use Rc for sharing.
Chapter Summary
  • Box<T> allocates a value on the heap and owns it, giving you a fixed-size pointer to store on the stack.
  • Box is essential for recursive types, since without it the compiler couldn't compute a finite size for the type.
  • Dereferencing a Box with * gives direct access to the inner value.
  • Box has single ownership semantics, just like other owned values -- it is dropped and freed automatically.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.