Hacker News new | ask | show | jobs
by exDM69 1316 days ago
For simple tasks you can get away without any external crates by using `Result<T, Box<dyn Error>>`. But it's much more comfortable to use thiserror or anyhow in the long run.

    fn read_string() -> std::io::Result<String> {
        Ok("123".to_owned())
    }

    fn main() -> Result<(), Box<dyn std::error::Error>> {
        let s = read_string()?; // io::Error
        let n = i32::from_str_radix(&s, 10)?; // num::ParseIntError
        println!("read number: {n}");
        Ok(())
    }
1 comments

Except you often need `Result<T, Box<dyn Error + Send + 'static>>` if you go that route. At the very least, you should create a type alias for it. I very much prefer the use of `anyhow` and/or `thiserror` depending on if I need typed errors.
And the reason it works in anyhow is ... They have those conversions: https://docs.rs/anyhow/latest/anyhow/struct.Error.html#impl-...