Module collections::boxed [] [src]

A pointer type for heap allocation.

Box<T>`Box`, casually referred to as a 'box', provides the simplest form of heap allocation in Rust. Boxes provide ownership for this allocation, and drop their contents when they go out of scope.

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)).

Recursive structures must be boxed, because if the definition of Cons`Cons` looked like this:

fn main() { Cons(T, List<T>), }
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 aCons. By introducing aBox, which has a defined size, we know how bigCons` needs to be.

Structs

Box

A pointer type for heap allocation.

ExchangeHeapSingleton [Unstable]

This the singleton type used solely for boxed::HEAP.

IntermediateBox [Unstable]

IntermediateBox represents uninitialized backing storage for Box`Box`.

Constants

HEAP [Unstable]

A value that represents the heap. This is the default place that the box`box` keyword allocates into when no place is supplied.

Traits

FnBox [Unstable]

FnBox`FnBoxis a version of theFnOnceintended for use with boxed closure objects. The idea is that where one would normally store aBoxin a data structure, you should useBox. The two traits behave essentially the same, except that aFnBoxclosure can only be called if it is boxed. (Note thatFnBoxmay be deprecated in the future ifBox` closures become directly usable.)

Functions

into_raw [Deprecated]

Consumes the Box`Box`, returning the wrapped raw pointer.