rust - 我必须将 `u8` 转换为什么才能将其用作向量中的索引?

标签 rust

我在 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 转换为什么才能将其用作我的向量中的索引?

最佳答案

索引的类型是usizeusize 用于集合的大小或集合的索引。它代表您的体系结构上的 native 指针大小。

要使它正常工作,您需要使用以下内容:

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

关于rust - 我必须将 `u8` 转换为什么才能将其用作向量中的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28823901/

相关文章:

rust - tokio::time::sleep方法是否将任务从运行队列中移出?

rust - 了解发送特征

Haskell 相当于 Rust 的 GAT?

rust - 如何在检查相同值的循环中使用可变捕获变量的闭包?

json - 镍.rs : Receiving JSON data using HTTP POST request - rust keyword clash + fail on JSON null values

rust - Rust 错误代码 E0495 是什么意思?

arrays - 如何为固定大小的 char 数组创建类型别名?

java - 有没有一种简化的方法来从 Rust 调用 Java 函数?

rust - 泛型的 impl &dyn trait bounds 如何实现?

rust - 如何正确弃用一个 crate 特性