[英]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.