Ndarray into_dimensionality error with ref

Hi everybody,

I am using ArrayD from the ndarray crate. Sometime I need to cast to a normal Array with a fix dimension therefore I need to use the into_dimensionality method. However this function can't be call from a reference, thus neither from a function with a reference, which is inconvenient because when working with array with generally want to pass reference rather than by copy.

Here is the code that don't work and I don't understand why:

use ndarray::{ArrayD,Ix1};

fn main(
  println!("Testing some code :°)");

  let a = ArrayD::<f64>::zeros(IxDyn(&[1]));
  let b =  a.into_dimensionality::<Ix1>().unwrap(); // every thing fine here

  let ref x = ArrayD::<f64>::zeros(IxDyn(&[1]));
  let y =  x.into_dimensionality::<Ix1>().unwrap(); // it fails here

with the following error message:

error[E0507]: cannot move out of `*x` which is behind a shared reference
  --> src/main.rs:18:12
18 |   let y =  x.into_dimensionality::<Ix1>().unwrap();
   |            ^ move occurs because `*x` has type `ArrayBase<OwnedRepr<f64>, Dim<IxDynImpl>>`, which does not implement the `Copy` trait

This behavior seems not to be documented anywhere, is it a bug ? Or is there an other way apply this method from a reference ?

Thanks in advance

It can be seen in the documentation for into_dimensionality() that it takes ownership of self in the function signature, rather than taking a reference. From a quick look at the source, it seems that is because it reinterprets the pointer to the array as a pointer to an array of a different dimensionality, so it is to avoid double ownership of the pointer.

It looks like you can apply view() to get a non-owning view of the array and then apply into_dimensionality() to that.

Indeed it was documented ! I Understand the the mechanism then, it is a bit annoying but I guess necessary. Thanks ! :slight_smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.