无法返回矢量切片 - 未实现ops :: Range <i32>

tom*_*sgd 3 rust

为什么以下Rust代码会出错?

fn getVecSlice(vec: &Vec<f64>, start: i32, len: i32) -> &[f64] {
    vec[start..start + len]
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误信息是

the trait `core::ops::Index<core::ops::Range<i32>>` is not implemented for the type `collections::vec::Vec<f64>` [E0277]
Run Code Online (Sandbox Code Playgroud)

在后来的Rust版本中,我得到了

error[E0277]: the trait bound `std::ops::Range<i32>: std::slice::SliceIndex<[f64]>` is not satisfied
 --> src/main.rs:2:9
  |
2 |         vec[start..start + len]
  |         ^^^^^^^^^^^^^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
  |
  = help: the trait `std::slice::SliceIndex<[f64]>` is not implemented for `std::ops::Range<i32>`
  = note: required because of the requirements on the impl of `std::ops::Index<std::ops::Range<i32>>` for `std::vec::Vec<f64>`
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用Vec类型模拟二维​​矩阵并返回对矩阵的不同行的引用.实现此目的的最佳方法是什么?

fjh*_*fjh 13

错误消息告诉您无法索引值为type的向量u32.Vec索引必须是类型usize,因此您必须将索引转换为该类型,如下所示:

vec[start as usize..(start + len) as usize]
Run Code Online (Sandbox Code Playgroud)

或者只是更改startlen参数的类型usize.

您还需要参考结果:

&vec[start as usize..(start + len) as usize]
Run Code Online (Sandbox Code Playgroud)


Grv*_*agi 5

为什么我们需要使用:

usize保证始终足够大以容纳数据结构中的任何指针或任何偏移量,而u32在某些体系结构上可能太小。

例如,在 32 位 x86 计算机上,usize = u32,而在 x86_64 计算机上,usize = u64.