Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downcasting a borrowed box

The downcast() method of Rust's Box type requires the call site to have full ownership of the Box instance. There doesn't appear to be an equivalent that can work with a borrowed reference. Is there a reason for this? Is there a workaround that will work on a borrowed instance?

like image 562
Flaise Avatar asked Feb 07 '17 00:02

Flaise


1 Answers

There is an alternative, but it's not a method of Box: it's Any::downcast_ref(). Thanks to deref coersion and Boxes Deref-impl, you can call T's methods on a Box<T> directly. Thus you can call Any::downcast_ref() on your Box<Any> directly:

let b: Box<Any> = Box::new(27u64);

// The type of `ref_a` and `ref_b` is `&u64`
let ref_a = b.downcast_ref::<u64>().unwrap();
let ref_b = b.downcast_ref::<u64>().unwrap();
println!("{} == {}", ref_a, ref_b);

There is also Any::downcast_mut() to obtain a mutable reference.

like image 143
Lukas Kalbertodt Avatar answered Nov 15 '22 09:11

Lukas Kalbertodt