Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enforce error handling in Rust when there is no actual result?

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?

like image 593
libra Avatar asked Sep 20 '25 12:09

libra


1 Answers

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.

like image 158
Aleksander Krauze Avatar answered Sep 23 '25 11:09

Aleksander Krauze