# 1.0.0[−][src]Module std::boxed

A pointer type for heap allocation.

`Box<T>`, 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

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

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

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

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

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);
    }Run

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>),Run

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`, which has a defined size, we know how big `Cons` needs to be.

## Structs

Box | A pointer type for heap allocation.

## Traits

FnBox

[
Experimental
]

`FnBox` is a version of the `FnOnce` intended for use with boxed closure objects. The idea is that where one would normally store a `Box<dyn FnOnce()>` in a data structure, you should use `Box<dyn FnBox()>`. The two traits behave essentially the same, except that a `FnBox` closure can only be called if it is boxed. (Note that `FnBox` may be deprecated in the future if `Box<dyn FnOnce()>` closures become directly usable.)

# Help

## Keyboard Shortcuts

`?`
  Show this help dialog
`S`
  Focus the search field
`↑`
  Move up in search results
`↓`
  Move down in search results
`↹`
  Switch tab
`⏎`
  Go to active search result
`+`
  Expand all sections
`-`
  Collapse all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g., `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g., `vec -> usize` or `* -> vec`)

Search multiple things at once by splitting your query with comma (e.g., `str,u8` or `String,struct:Vec,test`)