liveBook · Manning

Box

As explained in Rust in Action: Systems programming concepts and techniques

Box is Rust's owning smart pointer type for storing a value on the heap while keeping a pointer to it in the containing value.

`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

How Rust in Action: Systems programming concepts and techniques covers it

How deep it goes
Explains allocation, stack pointers, dereferencing, explicit drop, and why boxed trait objects have a known stack size.
Examples
Works through boxed integer addition, allocation and drop of boxed numbers, and a boxed error return type.
What it assumes
Builds from integer variables and addition, then introduces heap pointers and dereferencing; the error example uses Result and trait objects.
What you can do after
Apply it via Rust's Box::new to allocate a value, dereference it, and use Box<dyn Error> for differing errors.
How it connects
Connects Box to the heap, stack pointers, dereferencing, trait objects, and Result-based error handling.

Also explained in

Compare how 4 books explain Box →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust in Action: Systems programming concepts and techniques. The section links point to the parts of the book it draws on.