On this page
Box
Prev: smart_pointers | Up: smart_pointers | Next: `Arc`
Rel: smart_pointers, rust/builtins
Ref: Rust std — Box
Tags: #public #prog #rust #stdlib #smart_pointers #tier/core
Signature & Overview
Box<T>
Single-owner heap allocation (in prelude) used for recursive types and trait objects (Box<dyn Error>).
Notes & Pitfalls
- Single-owner heap allocation: Essential for recursive types (
enum List { Cons(i32, Box<List>), Nil }) and trait objects (Box<dyn Error>). - Zero reference-counting overhead: Freed deterministically when the
Boxgoes out of scope.
Example
enum List { Cons(i32, Box<List>), Nil }
fn sum(node: &List) -> i32 {
match node {
List::Cons(v, next) => v + sum(next),
List::Nil => 0,
}
}
fn main() {
let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
assert_eq!(sum(&list), 3);
}
Linked from
Related notes
- tuts/rust/std/smart_pointers/Arc Linked here; links to this page; shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/smart_pointers Linked here; links to this page; shared tags: #prog, #rust, #stdlib
- tuts/rust/builtins Linked here; shared tags: #prog, #rust
- tuts/rust/std/collections/BinaryHeap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/BTreeMap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/HashMap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/HashSet shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/VecDeque shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/error_and_fmt/Display shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/error_and_fmt/Error shared tags: #prog, #rust, #stdlib, #tier