【问题标题】:What must I cast an `u8` to in able to use it as an index in my vector?我必须将“u8”转换为什么才能将其用作向量中的索引?
【发布时间】:2015-03-03 04:04:46
【问题描述】:

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

【问题讨论】:

    标签: rust


    【解决方案1】:

    索引的类型为usizeusize 用于集合的大小或集合的索引。它代表架构上的本机指针大小。

    这是您需要使用它才能正常工作:

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

    【讨论】:

    • 感谢您的澄清!
    【解决方案2】:

    你应该把它转换成usize,我觉得它比 的your_vector[index_u8] 使用your_vector[index_u8 as usize]

    我个人认为x as usizeusize::from(x) 更具可读性,但这只是我的偏好。 在你的情况下: println!(“{}”, vec2d[row as usize][col as usize]);

    出现这种情况是因为 v[i] 确实被解析为 *(&amp;v + i),或者(向量的内存地址 + 索引)处的值。因为&amp;v是内存地址,所以索引i也必须是内存地址类型。 Rust 表示 usize 类型的内存地址。

    我知道这个问题已经得到解答,但我更喜欢x as usize 而不是usize::from(x)。决定权在你。

    【讨论】:

      猜你喜欢
      • 2020-05-16
      • 1970-01-01
      • 2017-12-16
      • 2023-02-05
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多