liveBook · Manning

Box

As explained in Idiomatic Rust

Box is a Rust standard-library owning pointer that stores a value on the heap and provides indirection.

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

How Idiomatic Rust covers it

How deep it goes
Explains pointer choice, trait-object coercion, and redundant nested allocation through focused code examples.
Examples
Demonstrates Vec<Box<dyn MyTrait>> for mixed implementations and contrasts Vec<Box<String>> with Vec<String>.
What you can do after
Apply Box to heap-allocate single-owner values, contain trait objects, and avoid unnecessary boxing inside Vec.
How it connects
Connects Box to heap allocation, ownership, Sized, trait objects, Vec, Rc, and Arc.

Also explained in

Compare how 4 books explain Box →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.