From::from to add Error trait, need explanation to understand

To add the trait Error to a value, I've seen this code:

type MyResult<T> = Result<T, Box<dyn Error>>;

fn parse_positive_int(val: &str)-> MyResult<usize> {
    match val.parse() {
        Ok(n) if n > 0 => Ok(n),
        _ => Err(From::from(val)),

but I don't understand how "From::from" can actually add the trait std::error::Error to val

Any help would be appreciated :slight_smile:

If you consult the documentation for From, you can find among its implementors

impl From<&'_ str> for Box<dyn Error>

That is, there is a conversion specifically for going from &str to Box<dyn Error>. (There is also one for String to Box<dyn Error>, and some other similar situations.)

The actual type that implements the Error trait is this private type StringError — first the &str is converted to String, and then it is wrapped in StringError. You can't see that type from outside, because it's always hidden behind dyn Error.


Also note that in cases such as this, From::from(val) is more commonly written val.into().

@kpreid Thanks for the explanation and link. I never though to go look at the source code, and yet, there was the answer :slight_smile: I am still learning how to navigate and decipher the doc, this helped alot!

@glts Indeed, the author of the code I listed also mention the 2 alternatives to the syntax, and one was the .into(). :slight_smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.