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
ベクター内のインデックスとして使用できるようにするには、を何にキャストする必要がありますか?
ベストアンサー1
インデックスは 型でありusize
、usize
コレクションのサイズ、またはコレクションへのインデックスに使用されます。これは、アーキテクチャ上のネイティブ ポインター サイズを表します。
これを適切に動作させるには、次のものを使用する必要があります。
println!("{}", vec2d[usize::from(row)][usize::from(col)]);