簡體   English   中英

無法在 u8 數組上使用 byteorder crate 中的方法:在當前范圍內找不到類型的方法

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

我正在嘗試使用 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`

我已經通讀了幾次關於 trait 的書章節,但不明白為什么這里不滿足 trait bound。

既不是[u8]也不是[u8; 4] [u8; 4]實現ReadBytesExt 文檔中所示,您可以使用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);

操場

任何實現Read類型都可以在這里使用,因為ReadBytesExt被實現為

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

由於&[u8]實現了Read您可以將其簡化為

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

甚至直接使用LittleEndian特性:

LittleEndian::read_u32(&my_array);

游樂場: (&my_array) , LittleEndian


您的代碼中還有其他一些錯誤:

  • [00000000,01010101,00100100,11011011]將換行。 改用二進制文字[0b0000_0000,0b0101_0101,0b0010_0100,0b1101_1011]
  • 您應該使用_使長數字更具可讀性
  • 變量應該在snake_case 使用my_array而不是myArray
  • 您在代碼中進行了不必要的賦值。 使用let my_array = [0b0000...

也可以看看:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM