简体   繁体   English

无法在 u8 数组上使用 byteorder crate 中的方法:在当前范围内找不到类型的方法

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

I'm trying to use a trait provided by the byteorder crate:我正在尝试使用 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.我已经通读了几次关于 trait 的书章节,但不明白为什么这里不满足 trait bound。

Neither [u8] nor [u8; 4]既不是[u8]也不是[u8; 4] [u8; 4] implements ReadBytesExt . [u8; 4]实现ReadBytesExt As shown in the documentation , you may use std::io::Cursor :文档中所示,您可以使用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 :任何实现Read类型都可以在这里使用,因为ReadBytesExt被实现为

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

Since &[u8] implements Read you can simplify it to由于&[u8]实现了Read您可以将其简化为

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

or even use the LittleEndian trait directly:甚至直接使用LittleEndian特性:

LittleEndian::read_u32(&my_array);

Playgrounds: (&my_array) , LittleEndian游乐场: (&my_array) , LittleEndian


You have some other mistakes in your code:您的代码中还有其他一些错误:

  • [00000000,01010101,00100100,11011011] will wrap. [00000000,01010101,00100100,11011011]将换行。 Use the binary literal instead : [0b0000_0000,0b0101_0101,0b0010_0100,0b1101_1011]改用二进制文字[0b0000_0000,0b0101_0101,0b0010_0100,0b1101_1011]
  • you should use _ to make long numbers more readable您应该使用_使长数字更具可读性
  • variables should be in snake_case .变量应该在snake_case Use my_array instead of myArray使用my_array而不是myArray
  • You do an unnecessary assignment in the code.您在代码中进行了不必要的赋值。 Use let my_array = [0b0000...使用let my_array = [0b0000...

See also:也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM