I am new to Rust, and I am trying to write simple bitwise replacer.
I have this code: 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)
}
I got errors like this one:
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]`
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.
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 forusize
and varioususize
ranges.This should answer both of your questions: indexing is not implemented for
u8
type and you need to castu8
tousize
.