RRust By Example
intermediateSmart Pointers

Box<T>

Allocate values on the heap with Box.

Box<T>

Allocate values on the heap with Box.

Difficulty

Intermediate

Code

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

fn main() {
    let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Cons(3, Box::new(List::Nil))))));

    let mut current = &list;
    loop {
        match current {
            List::Cons(val, next) => {
                println!("{}", val);
                current = next;
            }
            List::Nil => break,
        }
    }
}

Explanation

Box allocates on heap. Useful for recursive types.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the smart-pointers category to build a complete understanding of this topic.

More Smart Pointers Examples