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

后端 未结 2 1415
野的像风
野的像风 2021-01-13 09:19

Why does the following Rust code give an error?

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


        
2条回答
  •  醉梦人生
    2021-01-13 10:05

    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]
    

提交回复
热议问题