4 ms·
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
by exDM69 4y 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(())
}
- xedrac 4y agoExcept 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.
- WirelessGigabit 4y agoAnd the reason it works in anyhow is ... They have those conversions: https://docs.rs/anyhow/latest/anyhow/struct.Error.html#impl-From%3CError%3E-for-Box%3Cdyn%20StdError%20+%20%27static%3E https://docs.rs/anyhow/latest/anyhow/struct.Error.html#impl-...