Pointers
Box: smart pointer
All values in Rust are allocated on stack by default. Values wrapped by Box can be allocated on heap, Box<T> is a smart pointer to the value of type T.
When a box goes out of scope, its destructor is called, the inner object is destroyed, and the memory on the heap is freed.
Cheatsheet
let x = Box::new<value>;
let value: Type = *x;
fn return_trait() -> Box<dyn TraitType> { todo!() }
Questions
When to use smart pointers
- You want to own a dynamically sized object, like
Box<dyn SomeTrait> - You want to leak an object into
'staticlifetime - You want to produce an
ffipointer - You want to make recursive types