There is an alternative, but this is not the Box
method: it Any::downcast_ref()
. Thanks to the deref conversion and Box
es Deref
-impl, you can directly call T
methods on Box<T>
. This way you can directly call Any::downcast_ref()
on Box<Any>
:
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 get a mutable link.
source share