Rust Boxed values Using Boxed Values


Example

Because Boxes implement the Deref<Target=T>, you can use boxed values just like the value they contain.

let boxed_vec = Box::new(vec![1, 2, 3]);
println!("{}", boxed_vec.get(0));

If you want to pattern match on a boxed value, you may have to dereference the box manually.

struct Point {
    x: i32,
    y: i32,
}

let boxed_point = Box::new(Point { x: 0, y: 0});
// Notice the *. That dereferences the boxed value into just the value
match *boxed_point {
    Point {x, y} => println!("Point is at ({}, {})", x, y),
}