本文介绍了无法在 u8 数组上使用 byteorder crate 中的方法:在当前范围内找不到类型的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);
}

我收到一个错误:

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.

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.

推荐答案

既不是 [u8] 也不是 [u8;4] 实现 ReadBytesExt.如文档所示,您可以使用std::io::Cursor:

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);

游乐场

任何实现Read 可以在这里使用,因为 ReadBytesExt 实现为:

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

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

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

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

甚至直接使用 LittleEndian 特性:

or even use the LittleEndian trait directly:

LittleEndian::read_u32(&my_array);

游乐场:(&my_array), LittleEndian

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

You have some other mistakes in your code:

  • [00000000,01010101,00100100,11011011] 将换行.改用二进制文字:[0b0000_0000,0b0101_0101,0b0010_0100,0b1101_1011]
  • 您应该使用 _ 使长数字更具可读性
  • 变量应该在 snake_case 中.使用 my_array 而不是 myArray
  • 您在代码中做了一个不必要的赋值.使用 let my_array = [0b0000...
  • [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...

另见:

这篇关于无法在 u8 数组上使用 byteorder crate 中的方法:在当前范围内找不到类型的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 01:20