arrays - 为什么在使用 ReadBytesExt 从字节片中读取整数时出现错误“特征界限不满足”?
问题描述
以下 Rust 代码无法编译。
extern create byteorder;
use byetorder::{LittleEndian, ReadBytesExt};
fn main() {
let buf: [u8; 12] = [
0x00, 0x42, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0xc3, 0x00, 0x00, 0x30,
];
let id = &buf[0..1].read_u16::<LittleEndian>(); }
来自编译器的消息:
error[E0599]: no method named `read_u16` found for type `[u8]` in the current scope
--> src/main.rs:18:25
|
18 | let id = &buf[0..1].read_u16::<LittleEndian>();
| ^^^^^^^^
|
= note: the method `read_u16` exists but the following trait bounds were not satisfied:
`[u8] : byteorder::ReadBytesExt`
Stack Overflow 上有非常相似的问题,我已经复习过,但我的问题与这些问题略有不同,因为我试图u16
从切片中读取 a。在实践中,我不确定为什么我的示例有本质上的不同,我确信我遗漏了一些明显的东西。
具体来说,我不清楚我所得到的与此处接受的答案有何不同:
&[u8]
我说的时候不是也有&buf[0..1]
吗?
解决方案
您的代码调用read_u16()
数组而不是slice 。您可能打算在 on 上调用该方法&buf[0..1]
,但由于运算符优先级,您实际上是在 on 上调用它buf[0..1]
。这可以通过简单地添加一对括号来解决:
let id = (&buf[0..1]).read_u16::<LittleEndian>();
您的原始代码被解释为&(buf[0..1].read_u16::<LittleEndian>())
,这就是编译器抱怨该ReadBytesExt
特征未实现的原因[u8]
。
推荐阅读
- angular - 在 Angular(v2 及更高版本)反应形式表单数组中获取无效控件
- python - ValueError:“图像”必须具有 3 或 4 个维度
- graphql - Nextjs - 内容丰富 - 标签 - 动态页面
- nuxt.js - Nuxt fetch 钩子:为什么在服务器和客户端都触发?
- python - 我在 Linux/Ubuntu 系统上的 Virtualenv 中使用 Python3,pyaudio 已安装,但无法在 Jupyter Notebook 中导入
- php - Xdebug 在 Composer 插件中不可用
- c# - 无法让 MySQL Connector/NET 在 Ubuntu 上工作
- c# - CefSharp Winform MDI
- java - rust 和 JNI crate - 将 java 对象转换为字节数组并返回它们并返回空字段
- c++ - 我可以在容器中插入各种类型的元素吗?