|
|
|
|
|
by joshka
640 days ago
|
|
You can still do that in rust if you want / need to: https://play.rust-lang.org/?version=stable&mode=debug&editio... fn main() {
match process(&[0x34, 0x32]) {
Ok(n) => println!("{n} is the meaning of life"),
Err(e) => {
if e.is::<std::str::Utf8Error>() {
eprintln!("Failed to decode: {e}");
} else if e.is::<std::num::ParseIntError>() {
eprintln!("Failed to parse: {e}");
} else {
eprintln!("{e}");
}
}
}
}
fn process(bytes: &[u8]) -> Result<i32, Box<dyn std::error::Error>> {
let s = std::str::from_utf8(bytes)?;
let n = s.parse()?;
if n > 10 {
return Err(format!("{n} is out of bounds").into())
}
Ok(n)
}
In library code though that would make it generally more difficult to use the library, so the enum approach is more idiomatic. Then that comes out as match(e) {
MyError::Decode(e) => { ... }
MyError::ParseInt(e) => { ... }
...
}
etc, which is isomorphic to the style you miss. What you're perhaps missing the is that `except ...` is the just a language keyword to match on types, but that Rust prefers to encode type information as values, so that keyword just isn't needed.I feel you on the larval stage. Once you get past that, Rust starts to make a lot of sense. |
|