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

This example demonstrates how to use box in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

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

More Smart Pointers Examples