9

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?

Michael Ilyin
  • 717
  • 8
  • 15

1 Answers1

12

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:

trent
  • 25,033
  • 7
  • 51
  • 90