Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move the concrete value out of a Box<dyn Any>?

Tags:

rust

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?

like image 489
Michael Ilyin Avatar asked Jan 20 '20 13:01

Michael Ilyin


1 Answers

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:

  • How do I get an owned value out of a `Box`?
  • How to take ownership of Any:downcast_ref from trait object?
like image 92
trent Avatar answered Nov 11 '22 00:11

trent