I have value of type T in value: Box<dyn Any> and want to extract it. The only way I found is this:
let pv = value.downcast_mut::<T>();
let v = std::mem::replace(pv, T::default());
Is there a way to get v without requiring T to implement Default?
Box has its own downcast which returns a Result<Box<T>, Box<dyn Any>>. Once you have a Box<T> you can simply dereference it to get the T out. Here's one way to use it:
fn get<T: Any>(value: Box<dyn Any>) -> T {
let pv = value.downcast().expect("The pointed-to value must be of type T");
*pv
}
See also:
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