How do I get an owned value out of a `Box`?

Dereference the value:

fn unbox<T>(value: Box<T>) -> T {
    *value
}

There’s a nightly associated function into_inner you can use as well:

#![feature(box_into_inner)]
fn unbox<T>(value: Box<T>) -> T {
    Box::into_inner(value)
}

Way back in pre-1.0 Rust, heap-allocated values were very special types, and they used the sigil ~ (as in ~T). Along the road to Rust 1.0, most of this special-casing was removed… but not all of it.

This particular specialty goes by the name “deref move”, and there’s a proto-RFC about supporting it as a first-class concept. Until then, the answer is “because Box is special”.

See also:

Leave a Comment