Result, Option and the ? operator
Expected failures are values, not exceptions.
What you will be able to do
- Return Result for operations that can fail.
- Use ? to propagate errors that the caller should handle.
- Add context with anyhow or thiserror when building applications.
In plain English
Result<T, E> represents success or failure; Option<T> represents presence or absence. The ? operator propagates errors with a clear return type. Use unwrap only when a panic is truly a bug, not for user input.
use std::fs;
use std::io;
fn read_notes() -> Result<String, io::Error> {
let contents = fs::read_to_string("notes.txt")?;
Ok(contents)
}
fn main() {
match read_notes() {
Ok(notes) => println!("{notes}"),
Err(error) => eprintln!("Could not read notes: {error}"),
}
}Your turn
MediumRead a file with ?
Write a function that reads notes.txt and returns Result<String, io::Error>.
RUST · starter
fn read_notes() -> Result<String, std::io::Error> {
let value = String::new();
Ok(value)
}Check your understanding before moving on.
Knowledge checkQuestion 1
What does the ? operator do?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.