Closed jerry73204 closed 5 years ago
For .downcast_ref()
to return Some
, the types must match. In this case, a
has type ArrayD<f64>
. (Rust uses f64
as the default type for floating point numbers, not f32
.) So, that's the type that needs to be used when downcasting:
// Create array
let a = Array3::from_shape_vec((1, 2, 3), vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0])?.into_dyn();
println!("{:?}", a.shape());
// Box into any reference, and downcast back
let c: Box<dyn std::any::Any> = Box::new(a);
let aa = c.downcast_ref::<ArrayD<f64>>().unwrap(); // unwrap() works
If you want the array to contain f32
elements instead of f64
, you have to indicate that somehow, e.g. with a turbofish
let a = Array3::<f32>::from_shape_vec((1, 2, 3), vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0])?.into_dyn();
or adding a type annotation for a
let a: ArrayD<f32> = Array3::from_shape_vec((1, 2, 3), vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0])?.into_dyn();
Great. Since the compiler reports the undetermined float type {float}
in error message. I ignored that fact of default. Many thanks!
You're welcome, happy to help.
I came into the need of wrapping the array into
Box<Any>
type. It turns out thatAny::downcast()
always fails. Here is my reproduction:Above reproduction also fails on ArrayN (N = 1, 2, ...) types, not only dynamic-shaped array types. This example should satisfy all required type parameters. Anyone knows what's going on?
EDIT: typo in code