Box<T> stores a value on the heap while the box itself remains an ordinary owned value.

Program

Play the program to put a selected integer into a Box, dereference it, and compute from the boxed value.

value
box_heap_value.rs
Replay: real traced execution (multi-file project)
fn main() {
    let value = 12;
    let boxed = Box::new(value);
    let doubled = *boxed * 2;
    println!("{doubled}");
}
fn main() {
    let value = 7;
    let boxed = Box::new(value);
    let doubled = *boxed * 2;
    println!("{doubled}");
}
fn main() {
    let value = 20;
    let boxed = Box::new(value);
    let doubled = *boxed * 2;
    println!("{doubled}");
}
  1. value ← 12, boxed ← 12, doubled ← 24

    1fn main() {2    let valu→ 12e = 12; //@value=12, 7, 203    let boxe→ 12d = Box::new(valu12e);4    let double→ 24d = *boxe12d * 2;5    println!("{doubled}");6}
    output24
  1. value ← 7, boxed ← 7, doubled ← 14

    1fn main() {2    let valu→ 7e = 7;3    let boxe→ 7d = Box::new(valu7e);4    let double→ 14d = *boxe7d * 2;5    println!("{doubled}");6}
    output14
  1. value ← 20, boxed ← 20, doubled ← 40

    1fn main() {2    let valu→ 20e = 20;3    let boxe→ 20d = Box::new(valu20e);4    let double→ 40d = *boxe20d * 2;5    println!("{doubled}");6}
    output40
Box<T> `Box<T>` owns one heap allocation containing a `T`.
dereference `*boxed` reads the value stored inside the box.
ownership When `boxed` goes out of scope, Rust drops the heap allocation.