`Box<T>` stores a value on the heap and keeps a pointer to it on the stack. Create one with `Box::new(value)`. The “box” is not a container of bytes around the value; it is a pointer to the heap allocation. section 6.3.2
Add a boxed number
`let a: i32 = 40; let b: Box<i32> = Box::new(60);` The expression `a + b` does not compile: `b` is a box, not an `i32`. Use `a + *b` to dereference the pointer and add the stored value. section 6.3.2
Listing 6.7 Allocating and deallocating memory on the heap via Box<T>
1 use std::mem::drop; #1
2
3 fn main() {
4 let a = Box::new(1); #2
5 let b = Box::new(1); #2
6 let c = Box::new(1); #2
7
8 let result1 = *a + *b + *c; #3
9
10 drop(a); #4
11 let d = Box::new(1);
12 let result2 = *b + *c + *d;
13
14 println!("{} {}", result1, result2);
15 }
Follow three boxed integers through an addition, an explicit `drop(a)`, and another allocation. Both sums are `3`. section 6.3.2
A box also makes a trait object usable where a stack value must have a known size. `Box<dyn Error>` has a known size on the stack even when the concrete error it points to varies at runtime. section 8.5.1
Listing 8.12 Using a trait object in a return value
1 use std::fs::File;
2 use std::error::Error;
3 use std::net::Ipv6Addr;
4
5 fn main() -> Result<(), Box<dyn Error>> { #1
6
7 let _f = File::open("invisible.txt")?; #2
8
9 let _localhost = "::1"
10 .parse::<Ipv6Addr>()? #3
11
12 Ok(())
13 }
See `Box<dyn Error>` in a return type that handles errors from both opening a file and parsing an IPv6 address. section 8.5.1



