简体   繁体   English

如何将 integer 添加到 Rust 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>, _>`

If you use u64 instead of usize , you'll succeed.如果你使用u64而不是usize ,你会成功。 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 Rust 此片段的操场链接

It's because ndarray didn't implemented the Add trait for usize type.这是因为 ndarray 没有为usize类型实现Add trait。 It's implemented for i32 , u32 , and any other fixed sized integer types though.它是为i32u32和任何其他固定大小的 integer 类型实现的。

References参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM