3 ms·
I am not convinced that propagation is massively superior to unwrap in example code. Unwraps are nice because they give you error messages with line numbers, b
by eminence32 4y ago
I am not convinced that propagation is massively superior to unwrap in example code. Unwraps are nice because they give you error messages with line numbers, but line numbers don't seem to come for free with propagation.
Consider this code[1]:
fn main() {
let _my_num: u32 = "not a number".parse().unwrap();
}
Running this gives a slightly noisy/verbose message, but to my eyes it's pretty useful:
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }', src/main.rs:2:47
Compare this to similar code with propagation[2]:
fn main() -> Result<(), Box<dyn std::error::Error>> {
let _my_num: u32 = "not a number".parse()?;
Ok(())
}
Not only do I find the extra boilerplate distracting for this example code, but if I wanted to run this code in a playground, the error message seems worse as it omits the line number:
Error: ParseIntError { kind: InvalidDigit }
It's true that crates like anyhow[3] have robust support for producing backtraces (and I use them all the time in non-example code). But I'm not inclined to add an external crate to my examples just to avoid calling an unwrap().
[1] https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=20e2f21d6a296a09920525e6764837ff https://play.rust-lang.org/?version=stable&mode=debug&editio...
[2] https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=9a7e8a1a7c0e81de81cc9b7e3c9ce04b https://play.rust-lang.org/?version=stable&mode=debug&editio...
[3] https://crates.io/crates/anyhow https://crates.io/crates/anyhow