Search code examples
rustrust-ndarray

How to add an integer to a slice from Rust ndarray?


Let me try:

let mut a: Array2<usize> = Array2::zeros((20, 20));
let z = a.slice(s![.., 1]);
z += 1;

which gives:

error[E0368]: binary assignment operation `+=` cannot be applied to type `ArrayBase<ViewRepr<&usize>, _>`

Solution

  • If you use u64 instead of usize, you'll succeed. See the following example:

    use ndarray::{s, Array2};
    
    pub fn foo() -> Array2<u64> {
        let mut a: Array2<u64> = Array2::zeros((20, 20));
        let z = a.slice(s![.., 1]);
        z += 1;
        z
    }
    
    pub fn bar() -> Array2<usize> {
        let mut a: Array2<usize> = Array2::zeros((20, 20));
        let z = a.slice(s![.., 1]);
        z += 1; // NOTE: Fails!
        z
    }
    

    Rust playground link of this snippet

    It's because ndarray didn't implemented the Add trait for usize type. It's implemented for i32, u32, and any other fixed sized integer types though.

    Update: I've submit a PR to fix this issue, and it has been merged.

    References