我是Rust的新手,我正在尝试编写简单的按位替换器.
我有这个代码: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)
}
Run Code Online (Sandbox Code Playgroud)
我得到像这样的错误:
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]`
Run Code Online (Sandbox Code Playgroud)
我不明白为什么使用它u8作为索引值是非法的.如何转换u8为兼容类型?我甚至不知道哪种类型兼容.
您可以SliceIndex通过搜索Rust标准库来查看文档.文档页面底部的此特征的实现列表表明此特征是针对usize各种usize范围实现的.
这应该回答你的两个问题:索引没有实现u8类型,你需要转换u8为usize.
(get_part(TABLE[left as usize], left) << 4) + get_part(TABLE[right as usize], right)
Run Code Online (Sandbox Code Playgroud)