I’m doing this:
use anyhow::{Context, Result};
fn as_float(bytes: Vec<u8>) -> Result<f64> {
let a : &[u8; 8] = bytes.clone()
.try_into()
.context(format!("There is no data"))?;
Ok(f64::from_be_bytes(*a))
}
I’m getting:
error[E0277]: the trait bound `Vec<u8>: std::error::Error` is not satisfied
--> src/data.rs:76:14
|
76 | .context(format!("There is no data"))?;
| ^^^^^^^ the trait `std::error::Error` is not implemented for `Vec<u8>`
What’s wrong and how to solve this?
>Solution :
The error type for this conversion is the Vec itself. The idea is that if the conversion was unsuccessful you can still use the original Vec. But this means it does not implement std::error::Error, which is required for anyhow.
Instead of context(), map the error and create an anyhow error:
.try_into().map_err(|_| anyhow::anyhow!("there is no data"))
Or use the slice conversion methods that return TryFromSliceError, which does implement Error:
bytes.as_slice()
.try_into()
.context(format!("There is no data"))?;
As an aside, not that the conversion will fail if there is more than one element, not just if there are zero.