rust-ndarray / ndarray

ndarray: an N-dimensional array with array views, multidimensional slicing, and efficient operations
https://docs.rs/ndarray/
Apache License 2.0
3.6k stars 306 forks source link

Any::downcast() fails on array types #638

Closed jerry73204 closed 5 years ago

jerry73204 commented 5 years ago

I came into the need of wrapping the array into Box<Any> type. It turns out that Any::downcast() always fails. Here is my reproduction:

// 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<f32>>().unwrap(); // Error on unwrap()

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

jturner314 commented 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();
jerry73204 commented 5 years ago

Great. Since the compiler reports the undetermined float type {float} in error message. I ignored that fact of default. Many thanks!

jturner314 commented 5 years ago

You're welcome, happy to help.