为什么我不能使用 u8 作为 Rust 数组的索引值? [英] Why I can not use u8 as an index value of a Rust array?

查看:130
本文介绍了为什么我不能使用 u8 作为 Rust 数组的索引值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Rust 的新手,我正在尝试编写简单的按位替换器.

I am new to Rust, and I am trying to write simple bitwise replacer.

我有这个代码:

const TABLE: [u64; 8] = [
    0xC462A5B9E8D703F1,
    0x68239A5C1E47BD0F,
    0xB3582FADE174C960,
    0xC821D4F670A53E9B,
    0x7F5A816D093EB42C,
    0x5DF692CAB78143E0,
    0x8E25691CF4B0DA37,
    0x17ED05834FA69CB2,
];

fn get_part(u: u64, i: u8) -> u8 {
    ((u & (0xFu64 << (16 - i))) >> (16 - i)) as u8
}

fn process(o: u8, i1: u8, i2: u8) -> u8 {
    let left: u8 = o >> 4;
    let right: u8 = o & 0xF;
    (get_part(TABLE[left], left) << 4) + get_part(TABLE[right], right)
}

我遇到了这样的错误:

error[E0277]: the trait bound `u8: std::slice::SliceIndex<[u64]>` is not satisfied
  --> src/main.rs:19:15
   |
19 |     (get_part(TABLE[left], left) << 4) + get_part(TABLE[right], right)
   |               ^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
   |
   = help: the trait `std::slice::SliceIndex<[u64]>` is not implemented for `u8`
   = note: required because of the requirements on the impl of `std::ops::Index<u8>` for `[u64]`

error[E0277]: the trait bound `u8: std::slice::SliceIndex<[u64]>` is not satisfied
  --> src/main.rs:19:51
   |
19 |     (get_part(TABLE[left], left) << 4) + get_part(TABLE[right], right)
   |                                                   ^^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
   |
   = help: the trait `std::slice::SliceIndex<[u64]>` is not implemented for `u8`
   = note: required because of the requirements on the impl of `std::ops::Index<u8>` for `[u64]`

我不明白为什么使用 u8 作为索引值是非法的.如何将 u8 转换为兼容类型?我什至不知道哪种类型兼容.

I don't understand why it's illegal to use u8 as the index value. How can I convert u8 to a compatible type? I don't even know which type is compatible.

推荐答案

您可以通过 搜索 Rust 标准库.文档页面底部的此特征的实现列表 表示为 usize 和各种 usize 范围实现了这个特征.

You can look at the documentation for SliceIndex by searching the Rust standard library. The list of implementations of this trait at the bottom of the documentation page indicates that this trait is implemented for usize and various usize ranges.

这应该可以回答您的两个问题:u8 类型未实现索引,您需要将 u8 转换为 usize.

This should answer both of your questions: indexing is not implemented for u8 type and you need to cast u8 to usize.

(get_part(TABLE[left as usize], left) << 4) + get_part(TABLE[right as usize], right)

这篇关于为什么我不能使用 u8 作为 Rust 数组的索引值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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