Box<T> structv0.1.0

Source
One heap-allocated value of T, owned by exactly one holder.
pub struct Box<T> {
    // private fields
}

Move-only: its copy operation is prohibited and ~Box releases its allocation. Transfer one with <-; the source is then moved-out and reading it is rejected while compiling rather than at run time. The storage is released when the box is destroyed, at whichever scope exit, return, break, continue or overwriting assignment the value's life ends at.

Type parameters

NameDescription
Tthe type the box owns one of

Associated functions

Create

pub func Create(
    allocator: Allocator,
    value: T
) -> Box<T> ! AllocError

Puts value on the heap and hands back the box that owns it. allocator is borrowed for the call and kept in the box. value is consumed: on success the box owns it, and on failure it is destroyed rather than leaked. Runs in whatever time the allocator takes, and allocates exactly one block.

NameTypeDescription
allocatorAllocatorwhere the storage comes from
valueTthe value to move into it

Returns: the box, or why the allocator refused

Source

Methods

Get

pub func Get(self: &Box<T>) -> *var T

The value this box holds. self is borrowed and stays the caller's; the pointer borrows the box's storage and is valid only while the box is. Returns null for a box whose value has been taken out. Cannot fail. Runs in constant time and allocates nothing. The pointer dies with the box. Holding it past a move of the box is holding a pointer into released storage.

Returns: the address of the held value, or null when the box is empty

Source

IsEmpty

pub func IsEmpty(self: &Box<T>) -> bool

Whether this box still holds a value. self is borrowed. False only for a box whose value TryTake has moved out, which is a box that owns nothing and releases nothing. Cannot fail. Runs in constant time and allocates nothing.

Returns: whether the box holds nothing

Source

TryTake

pub func TryTake(
    self: &var Box<T>,
    destination: *var T
) -> bool

Moves the value out of the box, leaving the box empty, and releases the storage. self is borrowed mutably and is left empty. destination receives the value and must not be null; it is left unwritten when this reports false, which happens only for a box that is already empty. The storage goes back to the allocator here rather than at the box's destruction, so a caller taking the value out does not have to keep the box alive afterwards. Runs in whatever time the allocator takes.

NameTypeDescription
destination*var Treceives the held value

Returns: whether there was a value to take

Source

Destructor

func ~Box(self: &var Box<T>)

Destroys the value and releases its storage, if the box still holds any. Runs when the box's life ends, and does nothing for a box whose value was taken out. A box that was moved away is not destroyed where it used to live, so the storage is released exactly once.

Source