[][src]Module alloc_wg::boxed

A pointer type for heap allocation.

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

Examples

Move a value from the stack to the heap by creating a Box:

use alloc_wg::boxed::Box;

let val: u8 = 5;
let boxed: Box<u8> = Box::new(val);

Move a value from a Box back to the stack by dereferencing:

use alloc_wg::boxed::Box;

let boxed: Box<u8> = Box::new(5);
let val: u8 = *boxed;

Creating a recursive data structure:

use alloc_wg::boxed::Box;

#[derive(Debug)]
enum List<T> {
    Cons(T, Box<List<T>>),
    Nil,
}

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 looked like this:

This example deliberately fails to compile
Cons(T, List<T>),

It wouldn't work. This is because the size of a List depends on how many elements are in the list, and so we don't know how much memory to allocate for a Cons. By introducing a [Box<T, D>], which has a defined size, we know how big Cons needs to be.

Memory layout

For non-zero-sized values, a Box will use the Global allocator for its allocation if no allocator was specified. It is valid to convert both ways between a Box and a raw pointer allocated with the same allocator, given that the NonZeroLayout used with the allocator is correct for the type. More precisely, a value: *mut T that has been allocated with the Global allocator with Layout::for_value(&*value) may be converted into a box using Box::<T>::from_raw(value). For other allocators, [Box::<T>::from_raw_in(value, alloc)] may be used. Conversely, the memory backing a value: *mut T obtained from Box::<T>::into_raw may be deallocated using the specific allocator with NonZeroLayout::for_value(&*value).

Structs

Box

A pointer type for heap allocation.