我在 Rust 中有一个 2D 向量,我试图用动态 u8
变量对其进行索引。下面是我正在尝试做的一个例子:
fn main() {
let mut vec2d: Vec<Vec<u8>> = Vec::new();
let row: u8 = 1;
let col: u8 = 2;
for i in 0..4 {
let mut rowVec: Vec<u8> = Vec::new();
for j in 0..4 {
rowVec.push(j as u8);
}
vec2d.push(rowVec);
}
println!("{}", vec2d[row][col]);
}
但是,我得到了错误
error: the trait `core::ops::Index<u8>` is not implemented for the type `collections::vec::Vec<collections::vec::Vec<u8>>` [E0277]
在更高版本的 Rust 中,我得到
error[E0277]: the trait bound `u8: std::slice::SliceIndex<[std::vec::Vec<u8>]>` is not satisfied
--> src/main.rs:15:20
|
15 | println!("{}", vec2d[row][col]);
| ^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
|
= help: the trait `std::slice::SliceIndex<[std::vec::Vec<u8>]>` is not implemented for `u8`
= note: required because of the requirements on the impl of `std::ops::Index<u8>` for `std::vec::Vec<std::vec::Vec<u8>>`
我必须将 u8
转换为什么才能将其用作我的向量中的索引?
最佳答案
索引的类型是usize
; usize
用于集合的大小或集合的索引。它代表您的体系结构上的 native 指针大小。
要使它正常工作,您需要使用以下内容:
println!("{}", vec2d[usize::from(row)][usize::from(col)]);
关于rust - 我必须将 `u8` 转换为什么才能将其用作向量中的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28823901/