Box smart pointer is a pointer in Rust that allows you to allocate memory on the heap, even though the Box pointer itself exists in the stack.
Key notes:
- Box pointer owns the memory it points to, so, you’ll likely want to use it when you need to own the memory.
- When a Box goes out of scope, Rust automatically deallocates the memory on the heap.
- Box is used to store data when the size of the data is unknown at compile time or when the size of the data is too large to be stored on the stack.
- Heap allocation is also useful when you want to pass data between different threads.
To create a Box, you can use the Box::new()
function. This function takes the value that you want to store on the heap and returns a Box that points to the allocated memory. You can access the data stored in the Box by dereferencing it using the *
operator.
let x = Box::new(42);
println!("{}", *x); // prints 42
You can also use Box to store complex data structures, such as linked lists or trees. In these cases, the Box points to the first element of the data structure, and each element points to the next element. When the Box goes out of scope, Rust deallocates the memory for the entire data structure.
struct Node {
value: i32,
next: Option<Box<Node>>,
}
let mut head = Box::new(Node {
value: 1,
next: Some(Box::new(Node {
value: 2,
next: None,
})),
});
println!("{}", head.value); // prints 1
println!("{}", head.next.as_ref().unwrap().value); // prints 2