0

我正在使用ndarray并尝试对一些数组进行切片。这有效

    let y = arr2(&[[ 6,  5,  4],
                   [12, 11, 10]]);
    let ip = y.slice(s![0, ..]);
    println!("IP {}", ip); 

但是这个

    let y = arr2(&[[ 6,  5,  4],
                   [12, 11, 10]]);
    let ip = y.slice(s![0, ..]);
    println!("IP {}", ip[0]);

不编译。到底是怎么回事?

编译错误是:

Error[E0277]: the trait bound `i32: Dimension` is not satisfied 

....

println!("IP {}", ip[0]);
| ^^^^^ the trait `Dimension` is not implemented for `i32`
| = note: required because of the requirements on the impl of `std::ops::Index<i32>` for `ArrayBase<ViewRepr<&i32>, i32>`

有其他错误

error[E0308]: mismatched types
....
|         let ip = y.slice(s![0, ..]);
|                  ^^^^^^^^^^^^^^^^^^ expected `i32`, found struct `Dim`
|
= note: expected type `i32`
        found struct `Dim<[usize; 1]>`
4

1 回答 1

0

问题是整数文字是默认i32的,所以ip[0]告诉 Rust ip: Index<i32>,然后将slice's 参数的类型固定为i32,但类型应该是impl Dimension。(我不完全理解ndarray' 的索引/维度的类型层次结构,但这已经足够接近了,很有用。)要解决这个问题,只需简单地替换ip[0]ip[0_usize].

于 2022-02-24T18:40:54.873 回答