Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is purpose of `unwrap()` if the return value is not used?

I found this Rust code for getting a line from stdin:

use std::io;

fn main() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).unwrap();
    println!("Input: {}", line);
}

io::stdin().read_line(&mut line) sets the line variable to a line read from stdin. From my understanding, read_line() returns a Result value, which can be pattern-matched, or .unwrap() can be used to get the inner value if it is not an Err.

However, the returned value of read_line() is never used. Only the line string variable is used, but people use .unwrap() most of the time even if it is not used.

What is the purpose of unwrap() if the returned value is not used? Just to throw an error?

like image 285
Naetmul Avatar asked Jul 17 '17 11:07

Naetmul


1 Answers

What is the purpose of unwrap() if the returned value is not used? Just to throw an error?

Yes, but that's not all.

Ignoring potential errors is bad; there's a big difference between an empty line and a line that's not been read because of an error; for example in a typical "pipeline" command in a shell, the program needs to stop when it stops receiving input, otherwise the user has to kill it.

In C, ignoring errors is too easy. Many languages solve this by having exceptions, but Rust doesn't.

In order to avoid the issue plaguing C programs that it's too easy to forget to check the return code, normally Rust functions will bundle the expected return value and error in Result, so that you have to check it to get the return value.

There is one potential issue left, however: what if the caller doesn't care about the return value? Most notably, when the value is (), nobody really cares about it.

There is a bit of compiler magic invoked here: the Result structure is tagged with the #[must_use] attribute. This attribute makes it mandatory to do something with Result when it's returned.

Therefore, in your case, not only is unwrapping good, it's also the simplest way to "do something" and avoid a compilation warning.

like image 149
Matthieu M. Avatar answered Sep 28 '22 02:09

Matthieu M.