[英]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);
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]
_
to make long numbers more readable_
使长数字更具可读性snake_case
.snake_case
。 Use my_array
instead of myArray
my_array
而不是myArray
let my_array = [0b0000...
let my_array = [0b0000...
See also:也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.