Module collections::boxed
[−]
[src]
A pointer type for heap allocation.
Box<T>
`Box
Examples
Creating a box:
fn main() { let x = Box::new(5); }let x = Box::new(5);
Creating a recursive data structure:
#[derive(Debug)] enum List<T> { Cons(T, Box<List<T>>), Nil, } fn main() { let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil)))); println!("{:?}", list); }#[derive(Debug)] enum List<T> { Cons(T, Box<List<T>>), Nil, } fn main() { let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil)))); println!("{:?}", list); }
This will print Cons(1, Cons(2, Nil))
`Cons(1, Cons(2, Nil))`.
Recursive structures must be boxed, because if the definition of Cons
`Cons` looked like this:
Cons(T, List<T>),
It wouldn't work. This is because the size of a List
`Listdepends on how many elements are in the list, and so we don't know how much memory to allocate for a
` depends on how many elements are in the
list, and so we don't know how much memory to allocate for a Cons
`Cons. By introducing a
`. By introducing a Box
`Box, which has a defined size, we know how big
`,
which has a defined size, we know how big Cons
`Cons` needs to be.
Structs
Box |
A pointer type for heap allocation. |
Statics
HEAP |
[Unstable] A value that represents the heap. This is the default place that the |
Traits
FnBox |
[Unstable]
|
Functions
into_raw |
[Unstable] Consumes the |