Rust Foundations·Practice drills 5

Drill 12: Teach it — Error handling patterns

Explain the example to someone who has never seen it.

Intermediate 5 min read Lesson 125 of 300 Challenge included
What you will be able to do
  • Explain the example to someone who has never seen it.

Practice task

Explain the example to someone who has never seen it.

main.rsRust
use std::fs;
use thiserror::Error;

#[derive(Debug, Error)]
enum ReadError {
    #[error("file not found: {0}")]
    NotFound(String),
    #[error("could not read file: {0}")]
    Io(#[from] std::io::Error),
}

fn read_title(path: &str) -> Result<String, ReadError> {
    let text = fs::read_to_string(path)?;
    Ok(text.trim().to_string())
}

fn pick(values: Vec<i32>) -> Option<i32> {
    values.first().copied()
}

fn main() {
    match pick(vec![3, 5, 8]) {
        Some(first) => println!("first {}", first),
        None => println!("empty"),
    }

    match read_title("notes.txt") {
        Ok(title) => println!("title {}", title),
        Err(err) => println!("error {}", err),
    }
}
Your turn

Write your answer

Easy

Explain the example to someone who has never seen it.

TEXT · starter
Your answer…
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 125 of 300 · 0% of course