Box

Box is an owned pointer to data on the heap:

fn main() {
    let five = Box::new(5);
    println!("five: {}", *five);
}
5StackHeapfive

Box<T> implements Deref<Target = T>, which means that you can call methods from T directly on a Box<T>.

  • Box is like std::unique_ptr in C++.

    • Ownership: owns the value/object it points to.
    • Only one Box, one unique_ptr can own the data at a time.
    • Automatically deallocates memory when dropped/destroyed.
  • In the above example, you can even leave out the * in the println! statement thanks to Deref.