Rust Foundations·Ownership as a design tool

Result, Option and the ? operator

Expected failures are values, not exceptions.

Intermediate 14 min read Lesson 8 of 300 Challenge included
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.

files.rsRust
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

Read a file with ?

Medium

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 in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 8 of 300 · 0% of course