In Rust, errors are embedded in the return type of a function via Result<T,E>. That way, when I call a function that returns something of type T and I actually want to use that result, I have to somehow handle the error.
Now, in case I call some library function that generally does not return something, but might fail in a recoverable way, say it sets some flag in a complex structure. Now as I understand the way to write such a function is using Result<(), Error> as return type. But now the code calling this function has to explicitly handle the error and is not punished instantly if it does not. Doesn't this lead to me as a programmer having to always look twice at every functions signature in a library I'm using if I don't expect a result? In a language with exceptions I would still have to use some try-catch.
Can someone tell me if I just misunderstand something here, if there is maybe a better way to go about situations like that or if I am right and the programmer just has to be careful with library functions like that?
std::result::Result
is marked with #[must_use] attribute. This means that if you forget to handle Result
compiler will issue a warning. For example following code:
fn foo() -> Result<(), ()> {
todo!()
}
fn bar() {
foo();
}
compiles with warning:
warning: unused `Result` that must be used
--> src/lib.rs:6:5
|
6 | foo();
| ^^^^^
|
= note: this `Result` may be an `Err` variant, which should be handled
= note: `#[warn(unused_must_use)]` on by default
help: use `let _ = ...` to ignore the resulting value
|
6 | let _ = foo();
| +++++++
So you don't have to be extra careful just to avoid this situation. The compiler will help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With