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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With