【问题标题】:Cannot use methods from the byteorder crate on an u8 array: no method found for type in the current scope无法在 u8 数组上使用 byteorder crate 中的方法:在当前范围内找不到类型的方法
【发布时间】:2018-06-24 12:53:28
【问题描述】:

我正在尝试使用 byteorder crate 提供的特征:

extern crate byteorder;

use byteorder::{LittleEndian, ReadBytesExt};

fn main() {
    let mut myArray = [0u8; 4];
    myArray = [00000000, 01010101, 00100100, 11011011];

    let result = myArray.read_u32::<LittleEndian>();

    println!("{}", result);
}

我收到一个错误:

error[E0599]: no method named `read_u32` found for type `[u8; 4]` in the current scope
  --> src/main.rs:10:26
   |
10 |     let result = myArray.read_u32::<LittleEndian>();
   |                          ^^^^^^^^
   |
   = note: the method `read_u32` exists but the following trait bounds were not satisfied:
           `[u8; 4] : byteorder::ReadBytesExt`
           `[u8] : byteorder::ReadBytesExt`

我已经通读了几遍关于特质的书籍章节,无法理解为什么这里不满足特质绑定。

【问题讨论】:

    标签: rust


    【解决方案1】:

    [u8][u8; 4] 都没有实现 ReadBytesExt。如图in the documentation,可以使用std::io::Cursor

    let my_array = [0b00000000,0b01010101,0b00100100,0b11011011];
    let mut cursor = Cursor::new(my_array);
    
    let result = cursor.read_u32::<LittleEndian>();
    
    println!("{:?}", result);
    

    Playground

    任何实现Read 的类型都可以在这里使用,因为ReadBytesExt is implemented as

    impl<R: io::Read + ?Sized> ReadBytesExt for R {}
    

    由于&amp;[u8] 实现了Read,您可以将其简化为

    (&my_array[..]).read_u32::<LittleEndian>();
    

    甚至直接使用LittleEndian trait:

    LittleEndian::read_u32(&my_array);
    

    游乐场:(&amp;my_array)LittleEndian


    您的代码中还有其他一些错误:

    • [00000000,01010101,00100100,11011011] 将换行。使用binary literal instead[0b0000_0000,0b0101_0101,0b0010_0100,0b1101_1011]
    • 您应该使用_ 使长数字更具可读性
    • 变量应该在snake_case。使用my_array 而不是myArray
    • 您在代码中做了不必要的赋值。使用let my_array = [0b0000...

    另见:

    【讨论】:

      猜你喜欢
      • 2017-03-22
      • 2023-01-15
      • 2017-03-16
      • 2018-07-08
      • 1970-01-01
      • 2019-11-16
      • 1970-01-01
      • 2021-06-20
      • 1970-01-01
      相关资源
      最近更新 更多