【问题标题】:Error trying to slice bytes expected `usize`, found `u32`尝试对预期的“usize”字节进行切片时出错,发现“u32”
【发布时间】:2022-01-21 07:08:25
【问题描述】:

我试图切入缓冲区,但出现错误。

let mut buf = Vec::new();
let mut dst = [0u8; 4];
let read_index = 0;

dst.clone_from_slice(&buf[read_index..(read_index+3)]);
let length = u32::from_be_bytes(dst);
    
&buf[(read_index+4)..(read_index+length)]

error[E0308]: mismatched types
  --> src/main.rs:28:79
   |
28 |         let trade = root_as_fb_iq_feed_trade(&buf[(read_index+4)..(read_index+length)]);
   |                                                                               ^^^^^^ expected `usize`, found `u32`

error[E0277]: cannot add `u32` to `usize`
  --> src/main.rs:28:78
   |
28 |         let trade = root_as_fb_iq_feed_trade(&buf[(read_index+4)..(read_index+length)]);
   |                                                                              ^ no implementation for `usize + u32`
   |
   = help: the trait `Add<u32>` is not implemented for `usize`

【问题讨论】:

标签: rust


【解决方案1】:
let mut buf = Vec::new();
let read_index = 0;

dst.clone_from_slice(&buf[read_index..(read_index+3)]);
let length = usize::from_be_bytes(dst); // u32 -> usize
    
&buf[(read_index+4)..(read_index+length)]

usize 支持from_be_bytes 方法:The Rust doc of size::from_be_bytes

来自编译器的错误信息足够清晰,可以让您编写有效的代码。上面我提到的doc上也有说明,函数from_be_bytes只接受参数为[u8; 8],所以还有一处修改:

let mut buf = Vec::new();
let mut dst = [0u8; 8]; // Expand your buffer to the size of 8
let read_index = 0;

dst.clone_from_slice(&buf[read_index..(read_index+3)]);
let length = usize::from_be_bytes(dst);
    
&buf[(read_index+4)..(read_index+length)]
 

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
  • 让长度 = usize::from_be_bytes(dst); | ^^^ 期望一个固定大小为 8 个元素的数组,找到一个包含 4 个元素的数组
【解决方案2】:
let length = u32::from_be_bytes(dst);
let length_us = usize::try_from(length).unwrap();

【讨论】:

  • 如果这是您的问题的解决方案,最好添加此代码的确切作用来解决问题
猜你喜欢
  • 2016-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
  • 2017-09-28
  • 2022-01-24
  • 1970-01-01
相关资源
最近更新 更多