Search code examples
arraysrustarithmetic-expressions

Rust ndarray arithmetic operation unexpected type mismatch


I'm having a problem when trying to perform an arithmetic operation on two Array1s of the ndarray crate.

I have tried to reduce my problem to a the following reprex:

#[macro_use(array)]
extern crate ndarray;

use ndarray::Array1;

fn main() {
  let a: Array1<i8> = array![1, 2, 3];
  let baz = &a - array![1, 2, 3];
  println!("{:#?}", baz);
}

It fails with:

  |
8 |   let baz = &a - array![1, 2, 3];
  |                ^ expected struct `ndarray::ArrayBase`, found i8
  |

According to the documentation I should be able to subtract two Array1s and array! creates an Array1.

What I am doing wrong?


Solution

  • I should have read the documentation more carefully:

    &A @ &A which produces a new Array
    B @ A which consumes B, updates it with the result, and returns it
    B @ &A which consumes B, updates it with the result, and returns it
    C @= &A which performs an arithmetic operation in place
    

    There is no &A @ B situation for some reason. The second argument cannot be consumed. Either none is, or only the first one. As I don't want a to be consumed here, that is why I need to reference the return value of the array! macro.

    So the solution is:

    let baz = &a - &array![1, 2, 3];
    

    The compiler error is not really helping here though...