我在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]);
}
Run Code Online (Sandbox Code Playgroud)
但是,我得到了错误
error: the trait `core::ops::Index<u8>` is not implemented for the type `collections::vec::Vec<collections::vec::Vec<u8>>` [E0277]
Run Code Online (Sandbox Code Playgroud)
在后来的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>>`
Run Code Online (Sandbox Code Playgroud)
我必须将其u8
转换为能够将其用作向量中的索引吗?
Bri*_*ell 27
指数属于usize
; usize
用于集合的大小或集合的索引.它表示架构上的本机指针大小.
这是您需要使用此功能才能正常工作:
println!("{}",vec2d[row as usize][col as usize]);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6096 次 |
最近记录: |