You're going to want to downcast from a Box<dyn T> to a Box<T>, but keep in mind that it may not work because the memory size and alignment need to be correct. Hence, the use of downcast returns a Result.
Then, to go from Box<T> to T, just dereference the Box via *
let k: Box<i32> = Box::new(10 as i32)
let m: i32 = *k;
error[E0599]: no method named `downcast_ref` found for reference `&std::boxed::Box<GenericVar<dyn std::any::Any>>` in the current scope
--> src/main.rs:51:10
|
51 | .downcast_ref::<GenericVar<u8>>()
| ^^^^^^^^^^^^ method not found in `&std::boxed::Box<GenericVar<dyn std::any::Any>>`
error[E0277]: the size for values of type `(dyn std::any::Any + 'static)` cannot be known at compilation time
--> src/main.rs:11:17
|
11 | fn get_u16(var: &Box<GenericVar<dyn Any>>) -> Result<u16, String>
| ^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
...
39 | struct GenericVar<T: Any + 'static + Sized + Debug>
| - required by this bound in `GenericVar`
|
= help: the trait `std::marker::Sized` is not implemented for `(dyn std::any::Any + 'static)`
GenericVar is explicitly requiring its parameter to be Sized, so it can't be dyn Any. Maybe you want to change the bound in GenericVar from Sized (which is the default anyway) to ?Sized, which means "not only Sized".
You probably want to have Box<dyn Any> instead of Box<GenericVar<dyn Any>>. Box<GenericVar<dyn Any>> is not a useful type, as it won't have downcast methods and it will be difficult to initialize an unsized struct GenericVar<dyn Any>. I'm not sure where this type is coming from. If you use my previous suggestion in your playground, it works.