首页 > 解决方案 > 无法将切片索引转换为 u8 类型以插入到宏期望表达式中

问题描述

我刚开始编码Rust3 天,所以请耐心等待。我声明了一个宏,需要使用 2 个整数来索引向量并返回值。这 2 个整数将在 main 函数中从 2 个向量中提供,它们的值将插入宏中。我知道向量元素的类型是usize需要强制转换的,u8但这也不起作用。这是代码。

macro_rules! dummyMacro {
    ($x:expr, $y:expr) => {
        {
            let table = vec![1,2,3,4,5,6,7];

            table[$x + $y]
        }
    };
}

fn main() {
    let mut vectorOne: Vec<u8> = Vec::new();
    vectorOne.push(1);
    vectorOne.push(2);
    let mut vectorTwo: Vec<u8> = Vec::new();
    vectorTwo.push(1);
    vectorTwo.push(2);
    let mut vectorThree: Vec<u8> = vec![0,0];
    vectorThree[0] = dummyMacro!(vectorOne[0], vectorTwo[0]);
    println!("{:?}", vectorThree);    

}

错误

error[E0277]: the type `[{integer}]` cannot be indexed by `u8`
  --> src/main.rs:10:13
   |
10 |             table[$x + $y]
   |             ^^^^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
...
49 |     vectorThree[0] = dummyMacro!(vectorOne[0], vectorTwo[0]);
   |                      --------------------------------------- in this macro invocation
   |
   = help: the trait `std::slice::SliceIndex<[{integer}]>` is not implemented for `u8`
   = note: required because of the requirements on the impl of `std::ops::Index<u8>` for `std::vec::Vec<{integer}>`

我看过以下问题,但没有帮助

用于数组索引的正确类型是什么?

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

为什么我不能使用 u8 作为 Rust 数组的索引值?

标签: rustrust-cargo

解决方案


推荐阅读