无法返回向量切片 - ops::Range<i32>未实施 [英] Cannot return a vector slice - ops::Range<i32> is not implemented

查看:33
本文介绍了无法返回向量切片 - ops::Range<i32>未实施的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why does the following Rust code give an error?

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 中,我得到

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

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

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?

推荐答案

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

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]

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

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

您还需要参考结果:

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

这篇关于无法返回向量切片 - ops::Range&lt;i32&gt;未实施的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆