Rust Boxed values Using Boxes to Create Recursive Enums and Structs


Example

If you try and create a recursive enum in Rust without using Box, you will get a compile time error saying that the enum can't be sized.

// This gives an error!
enum List {
    Nil,
    Cons(i32, List)
}

In order for the enum to have a defined size, the recursively contained value must be in a Box.

// This works!
enum List {
    Nil,
    Cons(i32, Box<List>)
}

This works because Box always has the same size no matter what T is, which allows Rust to give List a size.