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

时间:2017-09-07 18:20:51

标签: rust

我是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)
}

我遇到了这样的错误:

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

1 个答案:

答案 0 :(得分:8)

您可以按searching the Rust standard library查看COROUTINE_SUSPENDED的文档。 documentation page底部的此特征的实施列表表明此特征是针对SliceIndex和各种usize范围实施的。

这应该回答您的两个问题:usize类型未实施索引,您需要将u8投射到u8

usize