Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

rust - What must I cast an `u8` to in able to use it as an index in my vector?

I have a 2D vector in Rust which I am trying to index with a dynamic u8 variable. An example of what I'm trying to do is below:

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]);
}

However, I get the error

error: the trait `core::ops::Index<u8>` is not implemented for the type `collections::vec::Vec<collections::vec::Vec<u8>>` [E0277]

In later versions of Rust, I get

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

What must I cast the u8 to in able to use it as an index in my vector?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Indices are of type usize; usize is used for sizes of collections, or indices into collections. It represents the native pointer size on your architecture.

This is what you need to use for this to work properly:

println!("{}", vec2d[usize::from(row)][usize::from(col)]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...