Sub topic 3
Handling the Result: expect and the ? operator
Reading from standard input can fail, so read_line returns a Result instead of a bare value. This chapter explains what that Result holds and the three ways to deal with it: match, expect, and the ? operator. It also covers how to choose between them.
It assumes you know basic Rust syntax, the difference between String and &str, and how Result and Option work at a basic level. It also assumes you can run a program with cargo run.
Why reading returns a Result
Standard input is not always a keyboard. It can be a file redirected with <, the output of another program, or a closed pipe. Reading from any of these can fail. The operating system may report an error, or the bytes may not be valid UTF-8, which String requires.
Rust does not hide these failures. The signature of Stdin::read_line is:
fn read_line(&self, buf: &mut String) -> io::Result<usize>io::Result<usize> is an alias for Result<usize, std::io::Error>. The two variants mean:
Ok(n): the read succeeded andnbytes were appended tobuf. The count includes the newline.Ok(0)means the input has ended, which a later chapter covers.Err(e): the read failed.eis astd::io::Errorwith a kind such asInvalidDataand a description.
The data you want ends up in the String you passed in, not in the return value. The Result only reports whether the read worked. Beginners often ignore it for that reason, so the compiler pushes back. Result is marked #[must_use], and this code produces a warning:
use std::io;
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input); // warning: unused `Result` that must be used
println!("{}", input.trim());
}The program still compiles and runs. If the read fails, though, it carries on with an empty or partial input and gives no sign that anything went wrong.
Option 1: match on the Result
The most explicit approach is to match on the value:
use std::io;
fn main() {
let mut input = String::new();
match io::stdin().read_line(&mut input) {
Ok(bytes) => println!("Read {bytes} bytes: {:?}", input),
Err(e) => eprintln!("Could not read input: {e}"),
}
}This gives you full control. You can retry, fall back to a default, or print a custom message. It is also the most verbose option. For a simple program where a read failure means there is nothing useful left to do, a shorter form is usually enough.
Option 2: expect
expect unwraps an Ok and returns the value inside. On Err it panics with your message followed by the error:
use std::io;
fn main() {
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("failed to read line");
println!("You typed: {}", input.trim());
}A panic prints a message to standard error and ends the program with a non-zero exit code (101). For a read error the message looks like this:
thread 'main' panicked at src/main.rs:6:10:
failed to read line: Error { kind: InvalidData, message: "stream did not contain valid UTF-8" }The exact text varies by Rust version and by error. The parts to rely on are your message and the debug form of the io::Error, which includes its kind.
unwrap does the same thing without a custom message. Prefer expect, because when it fails the message tells you which call went wrong.
expect suits small programs, scripts, and examples, where a read failure is unrecoverable anyway. It is a poor choice for library code or any function that other code calls. A panic takes the decision away from the caller, who may have wanted to retry or clean up.
Option 3: the ? operator
The ? operator is shorthand for "unwrap on success, return the error on failure". Writing expr? behaves roughly like this:
// Roughly what `let n = expr?;` expands to
let n = match expr {
Ok(value) => value,
Err(e) => return Err(From::from(e)),
};Here is a complete program that uses it:
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.trim());
Ok(())
}Three things changed from the expect version:
mainnow has the return typeio::Result<()>.- The call ends in
?instead of.expect(...). - The function ends with
Ok(()), because a function that returnsResultmust produce one on the success path.
Rules for ?
? works only inside a function whose return type can absorb the error. In a plain fn main(), which returns (), this fails to compile:
use std::io;
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input)?; // error
}The compiler reports that the ? operator can only be used in a function that returns Result or Option. The fix is to change the return type, as shown above.
The error type must also convert. The From::from(e) call in the expansion lets ? convert the error into the function's own error type. If the types are identical, as with io::Error in and io::Error out, nothing changes. If they differ, there must be a From implementation between them. This is why a function that mixes I/O and parsing errors needs a common error type. A later chapter uses Box<dyn Error> for that.
What main does with an Err
When main returns Err(e), the runtime prints Error: followed by the debug form of e to standard error and exits with code 1. No panic message or backtrace is involved. You can see this by feeding the program invalid UTF-8:
$ printf '\xff\n' | cargo run
Error: Custom { kind: InvalidData, error: "stream did not contain valid UTF-8" }The wording of the debug output differs between Rust versions, but the shape is the same. It is accurate and cheap to produce, but not friendly. If you want polished messages for users, handle the error yourself with match or map it to your own text.
Choosing between them
| Approach | On `Err` | Best for | Drawback |
|---|---|---|---|
| `match` | Runs code you wrote | Recovery, retries, custom messages | Verbose |
| `expect("msg")` | Panics with `msg` and the error | Quick programs, examples | Caller cannot react |
| `unwrap()` | Panics with only the error | Throwaway tests | No context in the message |
| `?` | Returns the error to the caller | Functions that return `Result` | Needs a compatible return type |
A practical rule: use ? in any function you expect to reuse or test, and use expect only in main of a program you do not plan to grow. Both are valid. Moving from expect to ? later is a small edit.
Putting ? to work in a helper
The ? operator becomes more useful once you move input code into a function. This helper prompts and reads one line, and it passes any failure to its caller:
use std::io::{self, Write};
fn ask(prompt: &str) -> io::Result<String> {
print!("{prompt}");
io::stdout().flush()?;
let mut input = String::new();
io::stdin().read_line(&mut input)?;
Ok(input.trim().to_string())
}
fn main() -> io::Result<()> {
let name = ask("Your name: ")?;
let city = ask("Your city: ")?;
println!("{name} lives in {city}.");
Ok(())
}Two different operations can fail here: flushing standard output and reading standard input. Both produce io::Error, so a single ? style covers them. Each ? is an early exit, so a failure on the flush skips the read. main uses ? again to pass any failure upward. Because the helper never decides what a failure means, main or a test can decide instead.
Edge cases
- Invalid UTF-8.
read_linefails with anInvalidDataerror if the input is not valid UTF-8. This is the most common real-world read error, and it is easy to trigger with binary data piped in. - The buffer after an error. After an
Err, theStringmay hold part of what was read. Treat its contents as unreliable and do not use them. - Interrupted reads. The standard library retries reads that a signal interrupted (
ErrorKind::Interrupted), so you do not need to handle that kind yourself forread_line. - Ok is not the same as data.
Ok(0)is a successful read that found the end of input. TheResultbeingOktells you nothing about whether there was a line to process. Check the count when it matters. ?in closures. A closure has its own return type. A?inside one returns from the closure, not from the enclosing function.
Summary
read_linereturnsio::Result<usize>. The text goes into yourString, and theResultreports success or failure.matchgives full control,expectpanics with a message you choose, and?returns the error to the caller.?needs a function that returns a compatibleResult, and it converts the error withFrom.- A
mainthat returnsErrprints the error and exits with code 1.
Exercise
This program does not compile. Why, and what is the smallest change that fixes it? use std::io; fn main() { let mut line = String::new(); io::stdin().read_line(&mut line)?; println!("{}", line.trim()); }
Show answer
The ? operator returns the error from the enclosing function, but main returns (), which cannot hold a Result. Change the signature to fn main() -> io::Result<()> and add Ok(()) as the last expression. Alternatively, replace ? with .expect("failed to read line").
Exercise
Write a function read_first_line() -> io::Result<String> that reads one line from standard input and returns it with the trailing newline removed. Why is it better to return the Result than to call expect inside the function?
Show answer
Example: fn read_first_line() -> io::Result<String> { let mut s = String::new(); io::stdin().read_line(&mut s)?; Ok(s.trim_end().to_string()) }. Returning the Result lets the caller decide what a failure means. It can retry, print a friendly message, or stop. A panic inside the function removes that choice and makes the function hard to test.