我必须将 `u8` 转换成什么才能将它用作向量中的索引? [英] What must I cast an `u8` to in able to use it as an index in my vector?

查看:58
本文介绍了我必须将 `u8` 转换成什么才能将它用作向量中的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Rust 中有一个 2D 向量,我正在尝试使用动态 u8 变量对其进行索引.我正在尝试做的一个例子如下:

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

但是,我收到错误

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

在更高版本的 Rust 中,我得到

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

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

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

推荐答案

索引类型为 usize;usize 用于集合的大小,或集合的索引.它代表您架构上的原生指针大小.

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

这篇关于我必须将 `u8` 转换成什么才能将它用作向量中的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆