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?
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.
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