如何将整数添加到 Rust ndarray 的切片中?
How to add an integer to a slice from Rust ndarray?
让我试试:
let mut a: Array2<usize> = Array2::zeros((20, 20));
let z = a.slice(s![.., 1]);
z += 1;
给出:
error[E0368]: binary assignment operation `+=` cannot be applied to type `ArrayBase<ViewRepr<&usize>, _>`
如果您使用 u64
而不是 usize
,您就会成功。请参阅以下示例:
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
这是因为 ndarray 没有为 usize
类型实现 Add
特征。它是为 i32
、u32
和任何其他固定大小的整数类型实现的。
更新:I've submit a PR to fix this issue, and it has been merged.
参考资料
让我试试:
let mut a: Array2<usize> = Array2::zeros((20, 20));
let z = a.slice(s![.., 1]);
z += 1;
给出:
error[E0368]: binary assignment operation `+=` cannot be applied to type `ArrayBase<ViewRepr<&usize>, _>`
如果您使用 u64
而不是 usize
,您就会成功。请参阅以下示例:
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
这是因为 ndarray 没有为 usize
类型实现 Add
特征。它是为 i32
、u32
和任何其他固定大小的整数类型实现的。
更新:I've submit a PR to fix this issue, and it has been merged.