Sub topic 3
Box<T>: putting a value on the heap
This chapter assumes you know Rust ownership, moves, and borrowing, the difference between stack and heap memory, and basic generics. It covers Box<T>, the simplest smart pointer. Later chapters use it for recursive types and trait objects.
What Box does
Box<T> is a smart pointer that owns one value of type T stored on the heap. The box itself lives wherever you put it, usually on the stack, and holds only the address of the heap data. The box has no other overhead and no extra features.
fn main() {
let b = Box::new(5);
println!("b = {}", b);
}Box::new(5) allocates space on the heap, moves 5 into it, and returns the box. Printing works because Box<T> implements Display when T does. When b goes out of scope, Rust frees the heap memory and the box itself.
Ownership still applies
A box owns its data, so the ordinary ownership rules apply to it. Assigning a box to another variable moves it, and the old variable can no longer be used.
fn main() {
let a = Box::new(String::from("hello"));
let b = a;
// println!("{}", a); // error: borrow of moved value: `a`
println!("{}", b);
}Only one owner exists at a time. That is the main difference from Rc<T>, which a later chapter covers.
Reading and changing the value
Use the dereference operator * to reach the value inside. A mutable box lets you change it.
fn main() {
let mut count = Box::new(10);
*count += 1;
println!("count = {}", *count);
let moved_out: i32 = *count;
println!("moved_out = {}", moved_out);
}The program prints count = 11 and then moved_out = 11. Here i32 is Copy, so the last line copies the number. For a non-Copy type, *boxed moves the value out and consumes the box. Box is the one smart pointer that supports this move-out dereference.
When to use Box
Use Box<T> in three situations:
- The compiler cannot know a type's size at compile time, and you need a value of that type. A recursive type is the usual case, and the next chapter covers it.
- You want to hold a value through a trait it implements, not through its concrete type. This is a trait object,
Box<dyn Trait>. - You have a large value and want to transfer ownership without copying the data. Moving a box copies only the pointer. Measure first, because the compiler often optimizes moves already.
Common mistakes
- Boxing small values for no reason. An
i32in a box costs an allocation and an extra pointer hop, and you gain nothing. - Expecting a box to be shared. It is not. If you need several owners, you need
Rc<T>. - Using the box after moving it. The error "borrow of moved value" is the ownership rules working as intended.
Exercise
What does let c = Box::new(String::from("hi")); let d = c; do to c, and what happens to the heap memory when d goes out of scope?
Show answer
The assignment moves the box from c to d, so c can no longer be used. When d goes out of scope, Rust drops the box and frees the heap memory holding the string. The memory is freed once, because only one owner exists.
Exercise
Why is Box<T> a smart pointer and not just a reference?
Show answer
A reference borrows data owned by someone else. A Box<T> owns its heap data, and it frees that data automatically when the box goes out of scope.