In this lesson, you will learn how to use Box<T> to move data from the limited stack to the flexible heap.
Why move data to the heap?
As you’ve learned, the stack is fast and managed automatically, but it has a strict size limit. If you have a massive piece of data, keeping it on the stack can lead to a "stack overflow." Furthermore, sometimes you need to store data of a size that the compiler doesn't know at compile time.
The Box<T> is a "smart pointer." It is a small object that lives on the stack, but it contains an address pointing to data stored on the heap.
Using Box in Practice
When you wrap a value in a Box::new(), you are explicitly telling Rust to allocate that data on the heap. Even though the data is now in a different location in memory, the ownership rules remain exactly the same. The Box owns the heap memory, and when the Box goes out of scope, Rust automatically cleans up that heap memory for you.
Consider this example:
fn main() {
// Large data stored on the heap
let my_data = Box::new([0; 1000]);
// my_data still owns the array, and the
// memory will be freed when my_data is dropped.
println!("Data is safely on the heap: {:?}", my_data[0]);
}
Ownership and the Box
Because Box follows standard ownership rules, if you assign my_data to a new variable, the ownership moves. The actual data on the heap does not get copied; only the pointer (the address) is moved. This makes moving large structures very efficient, as you aren't copying the data itself, just the small "reference" stored in the Box.
By using Box, you gain the ability to manage memory location without losing the safety guarantees or the clear ownership semantics you’ve worked with so far.
Key Takeaway: Box<T> allows you to store data on the heap while maintaining Rust’s strict ownership rules and automatic memory cleanup.