Cannot use methods from the byteorder crate on an u8 array: no method found for type in the current scope

跟風遠走 提交于 2020-02-23 07:29:10

问题


I'm trying to use a trait provided by the 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);
}

I'm getting an error:

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`

I've read through the book chapter on traits a couple of times and can't understand why the trait bound isn't satisfied here.


回答1:


Neither [u8] nor [u8; 4] implements ReadBytesExt. As shown in the documentation, you may use 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

Any type which implements Read can be used here, since ReadBytesExt is implemented as:

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

Since &[u8] implements Read you can simplify it to

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

or even use the LittleEndian trait directly:

LittleEndian::read_u32(&my_array);

Playgrounds: (&my_array), LittleEndian


You have some other mistakes in your code:

  • [00000000,01010101,00100100,11011011] will wrap. Use the binary literal instead: [0b0000_0000,0b0101_0101,0b0010_0100,0b1101_1011]
  • you should use _ to make long numbers more readable
  • variables should be in snake_case. Use my_array instead of myArray
  • You do an unnecessary assignment in the code. Use let my_array = [0b0000...

See also:

  • You don't need a cursor most of the time


来源:https://stackoverflow.com/questions/51010139/cannot-use-methods-from-the-byteorder-crate-on-an-u8-array-no-method-found-for

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!