首页 > 解决方案 > 为什么在使用 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]) 的缓冲区转换为整数?

&[u8]我说的时候不是也有&buf[0..1]吗?

标签: arrayscastingreferencerustslice

解决方案


您的代码调用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]


推荐阅读