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

时间:2015-04-27 09:37:53

标签: rust

为什么以下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类型模拟二维矩阵,并返回对矩阵不同行的引用。实现此目的的最佳方法是什么?

2 个答案:

答案 0 :(得分:13)

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

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

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

您还need to take a reference to the result

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

答案 1 :(得分:0)

我们为什么需要使用:

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

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