Box
Box is an owned pointer to data on the heap:
fn main() { let five = Box::new(5); println!("five: {}", *five); }
Box<T> implements Deref<Target = T>, which means that you can call methods
from T directly on a Box<T>.
-
Boxis likestd::unique_ptrin C++.- Ownership: owns the value/object it points to.
- Only one
Box, oneunique_ptrcan own the data at a time. - Automatically deallocates memory when dropped/destroyed.
-
In the above example, you can even leave out the
*in theprintln!statement thanks toDeref.