Box is an owning smart pointer for heap-allocated values. Use it when you need heap allocation without shared ownership, or when a value that may be unsized must fit inside a sized container. section 10.8 section 2.2.6
A Box can hold a trait object: construct it with a concrete type, then coerce it to Box<dyn MyTrait>. This lets a Vec hold values of different types that implement the same trait. section 2.2.6
let mut v = Vec::<Box<dyn MyTrait>>::new();
v.push(Box::new(MyStruct1 {})); #1
v.push(Box::new(MyStruct2 {})); #2
v.iter().for_each(|i| i.trait_hello()); #3
// v.iter().for_each(|i| i.struct_hello()); error! #4
This example stores two different implementations in one vector of boxed trait objects and calls their shared trait method. section 2.2.6
Choose the pointer for the ownership you need: Box for a single owner, Rc for shared ownership within a thread, and Arc for shared ownership across threads. Avoid boxing values inside Vec without a reason; both Vec and Box allocate for their contents. section 10.8 section 10.8
Listing 10.14 Overusing smart pointers
let mut string_box_vec: Vec<Box<String>> =
vec![Box::new( #1
String::from("unecessarily boxed string") #1
)]; #1
let mut string_vec: Vec<String> =
vec![String::from("this is okay")]; #2
let boxed_string = string_box_vec.remove(0); #3
let normal_string = string_vec.remove(0); #4
Compare Vec<Box<String>> with Vec<String> to see the redundant boxing pattern and its alternative. section 10.8



