0

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Michael Stone
  • 177
  • 1
  • 8

1 Answers1

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:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Tim Diekmann
  • 7,755
  • 11
  • 41
  • 69