不能 return 向量切片 - ops::Range<i32> 未实现

Cannot return a vector slice - ops::Range<i32> is not implemented

为什么下面的 Rust 代码会报错?

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

我收到的错误信息是

the trait `core::ops::Index<core::ops::Range<i32>>` is not implemented for the type `collections::vec::Vec<f64>` [E0277]

在更高版本的 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>`

我正在尝试使用 Vec 类型和 return 对不同行的引用来模拟二维矩阵 matrix.What 是实现此目的的最佳方法吗?

错误消息告诉您不能索引到具有类型 u32 值的向量。 Vec 索引必须是 usize 类型,因此您必须像这样将索引转换为该类型:

vec[start as usize..(start + len) as usize]

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

你也:

&vec[start as usize..(start + len) as usize]

为什么需要usize:

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

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