为什么下面的 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
输入并返回对矩阵不同行的引用。实现此目的的最佳方法是什么?
错误消息告诉您无法对具有类型值的向量进行索引u32
. Vec
索引必须是类型usize
,所以你必须将索引转换为该类型,如下所示:
vec[start as usize..(start + len) as usize]
或者只是改变类型start
and len
论点usize
.
你也需要参考结果:
&vec[start as usize..(start + len) as usize]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)