O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Box<T>

The generic type box in the standard library gives us the simplest way to allocate values in the heap. If you're familiar with the concept of boxing and unboxing from other languages, this is the same.

The box itself does not implement the Copy trait, which makes it a move type. This means, like for other move types, that if you make a new binding to the existing box, the earlier binding gets invalidated.

To get a new box, do as you would for any other container type: call the static new method. To unbox, use the * operator:

let boxed_one = Box::new(1); let unboxed_one = *boxed_one; 

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required