Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can't I use anyhow::Context together with try_into()?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading