intermediateSmart Pointers
Box<T>
Allocate values on the heap with Box.
Box<T>
Allocate values on the heap with Box.
Difficulty
Intermediate
Code
rust
enum List {
Cons(i32, Box<List>),
Nil,
}
fn main() {
let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Cons(3, Box::new(List::Nil))))));
let mut current = &list;
loop {
match current {
List::Cons(val, next) => {
println!("{}", val);
current = next;
}
List::Nil => break,
}
}
}Explanation
This example demonstrates how to use box
Key Concepts
- Rust's strong type system catches errors at compile time
- Ownership and borrowing rules ensure memory safety
- Pattern matching makes code expressive and exhaustive
Related Topics
Browse more examples in the smart-pointers category to build a complete understanding of this topic.