Generics, errors and strings

I am trying to implement some custom errors for my application.

Today I was skimming through the standard library to see how it was handled there and found that a confusing constructor in std::io::errors

impl Error {
    pub fn new<E>(kind: ErrorKind, error: E) -> Error
        where E: Into<Box<error::Error+Send+Sync>>
         // ...

Which can be used like this:

Error::new(ErrorKind::InvalidInput, "invalid argument")
Error::new(ErrorKind::InvalidInput, e)  // Where `e` is some other error

This is super convenient but I don't understand how it works, specially in the case of the string literal.
From what I understand from the str documentation, it doesn't implement none of the traits required by the new signature.

What is happening?

1 Like

There’s a impl<‘a> From<&’a str> for Box<Error> in stdlib. Then there’s also the blanket impl<T, U> Into<U> for T where U: From<T> - this means you automatically get an “inverse” Into once you implement From. In this case, it means you effectively get a impl<‘a> Into<Box<Error>> for &’a str, and that’s how it works out here.

1 Like

Thank you, that really helped.

Your answer also lead me to the documentation for the From trait, which also has a lot of information that I missed previously.