为何无法将anyhow::Context与try_into()配合使用?
问题原因
你代码里的错误源于bytes.clone().try_into()这一步的类型转换逻辑:
- 试图直接将
Vec<u8>转换为&[u8;8],导致try_into()返回的错误类型是Vec<u8>,而Vec<u8>并未实现std::error::Errortrait。 anyhow的context方法要求被包裹的错误类型必须实现Error,因此编译器抛出E0277错误。
另外,bytes.clone()属于多余操作——我们只需要读取Vec<u8>的切片引用,无需克隆整个向量。
解决方法
有两种简洁的修正方式:
方式一:基于切片引用转换
先把Vec<u8>转为不可变切片&[u8],再尝试转换为固定长度的切片引用&[u8;8],此时错误类型为TryFromSliceError(已实现Error trait),可正常使用context:
use anyhow::{Context, Result}; fn as_float(bytes: Vec<u8>) -> Result<f64> { let a: &[u8; 8] = bytes.as_slice() .try_into() .context("There is no data")?; Ok(f64::from_be_bytes(*a)) }
方式二:直接转换为数组
如果不需要保留原Vec<u8>的所有权,可直接将其转换为[u8;8]数组,错误类型同样为TryFromSliceError,代码更简洁:
use anyhow::{Context, Result}; fn as_float(bytes: Vec<u8>) -> Result<f64> { let a: [u8; 8] = bytes.try_into() .context("There is no data")?; Ok(f64::from_be_bytes(a)) }
内容的提问来源于stack exchange,提问作者yegor256
相关产品推荐
相关产品推荐

