Cannot return a vector slice - ops::Range is

2019-02-19 05:08发布

问题:

Why does the following Rust code give an error?

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

The error message I get is

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

In later versions of Rust, I get

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>`

I'm trying to simulate a 2 dimensional matrix using the Vec type and return references to the different rows of the matrix.What is the best way to achieve this?

回答1:

The error messages tells you that you can't index into a vector with values of type u32. Vec indices have to be of type usize, so you have to cast your indices to that type like this:

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

or just change the type of the start and len arguments to usize.

You also need to take a reference to the result:

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


标签: rust