我是新手,我正在try 编写简单的位替换程序.

我有这个密码:

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转换为兼容类型?我甚至不知道哪种类型是兼容的.

推荐答案

您可以查看SliceIndex x searching the Rust standard library的文档.documentation page底部的这个特性的实现列表表明这个特性是针对usize和各种usize范围实现的.

这应该能回答你的两个问题:索引不是为u8类型实现的,你需要将u8转换为usize.

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

Rust相关问答推荐

访问Rust中的隐藏变量

如何装箱生命周期相关联的两个对象?

rust 蚀生命周期 行为

在Rust中赋值变量有运行时开销吗?

为什么Rust函数的移植速度比C++慢2倍?

如何在 struct 的自定义序列化程序中使用serde序列化_WITH

integer cast as pointer是什么意思

你是如何在铁 rust 一侧的金牛座获得应用程序版本的?

Trait bound i8:来自u8的不满意

你能在Rust中弃用一个属性吗?

考虑到Rust不允许多个可变引用,类似PyTorch的自动区分如何在Rust中工作?

为什么 js_sys Promise::new 需要 FnMut?

如何以与平台无关的方式将OsString转换为utf-8编码的字符串?

为什么在 rust 中删除 vec 之前应该删除元素

预期的整数,找到 `&{integer}`

为什么拥有 i32 所有权的函数需要它是可变的?

RAII 模式的 Rust 解决方案,用于在 new() 和 drop() 上修改另一个对象

使用 serde_json 进一步处理字段

没有通用参数的通用返回

Rust 内联 asm 中的向量寄存器:不能将 `Simd` 类型的值用于内联汇编