Sub topic 3
Handling the Result: expect and the ? operator
This chapter assumes you know basic Rust syntax, how String and &mut references work, and the basics of Result. It also assumes you can run a program with cargo run. The previous chapter showed read_line filling a String. This chapter covers the value read_line returns and what to do with it.
What read_line returns
read_line returns io::Result<usize>. That is shorthand for Result<usize, io::Error>.
Ok(n)means the read worked.nis the number of bytes appended to the buffer, including the newline.Err(e)means the read failed.eis anio::Errorthat describes why.
Reading can fail for a few reasons. The most common one in practice is input that is not valid UTF-8, which produces an error of kind InvalidData. Reaching the end of input is not a failure. It gives Ok(0), which a later chapter uses.
Option 1: expect
expect unwraps an Ok value. On Err, it panics and prints your message followed by the error.
use std::io;
fn main() {
let mut input = String::new();
let bytes = io::stdin()
.read_line(&mut input)
.expect("failed to read line");
println!("Read {bytes} bytes: {:?}", input);
}This is fine for small scripts and examples. The program stops with a clear message, and you write no extra code. Prefer expect to unwrap, because the message tells you which call failed.
Option 2: the ? operator
The ? operator handles the Err case differently. It returns the error from the current function, so the caller decides what to do. On Ok, it gives you the inner value.
use std::io;
fn main() -> io::Result<()> {
let mut input = String::new();
let bytes = io::stdin().read_line(&mut input)?;
println!("Read {bytes} bytes: {:?}", input);
Ok(())
}Two changes make this work. main now returns io::Result<()>, and it ends with Ok(()). If read_line fails, main returns the Err, and Rust prints the error and exits with a non-zero status.
The same pattern works in your own helper functions. The caller of the helper then makes the decision:
use std::io;
fn read_name() -> io::Result<String> {
let mut name = String::new();
io::stdin().read_line(&mut name)?;
Ok(name.trim().to_string())
}
fn main() {
match read_name() {
Ok(name) => println!("Hello, {name}!"),
Err(e) => eprintln!("Could not read your name: {e}"),
}
}Choosing between them
| Situation | Use |
|---|---|
| Short script or example, a failure should just stop it | `expect` |
| Helper function that others call | `?` |
| `main` that does several fallible steps | `?` with `main` returning `Result` |
| You want to print your own message and continue | `match` on the `Result` |
Common errors
- Using
?in a function that returns(). The compiler reports that?can only be used in a function that returnsResultorOption. Change the return type toio::Result<()>and addOk(())at the end. - Ignoring the result. Writing
io::stdin().read_line(&mut input);compiles, but you get anunused_must_usewarning. The error is silently dropped. Always handle it. - Mixing error types with
?. In a function returningio::Result<T>, you cannot apply?to aparseresult.ParseIntErrordoes not convert toio::Error. Handle the parse withmatch, as in the next chapters, or useBox<dyn Error>, which a later chapter covers. - Forgetting
mut.read_line(&mut input)needslet mut input.
Exercise
A function is declared as fn ask() -> String and its body contains io::stdin().read_line(&mut s)?;. Why does this fail to compile, and what is the smallest change that fixes it?
Show answer
? returns the Err from the function, but ask returns String, which cannot hold an error. Change the return type to io::Result<String> and return Ok(s) at the end. The caller must then handle the Result. As an alternative, replace ? with .expect("failed to read line") and keep the String return type.