Easily convert third party Errors to String

If a type implements std::error::Error, it also implements Display:

pub trait Error: Debug + Display {
    // ...
}

The ToString trait, which provides the method to_string, is implemented for any type that implements Display.

Thus, any type that implements Error can be converted to a String via to_string:

use git2; // 0.13.2

fn do_stuff() -> Result<i32, String> {
    let repo = git2::Repository::open(".").map_err(|e| e.to_string())?;
    unimplemented!()
}

Well it turns out there is a bit in the Rust book about this. It doesn't allow you to convert to String, but apparently all Error types can be converted to Box<Error> so I just replaced String with that. It's cleaner too.

Tags:

Rust