Rust Foundations·Practice drills 9

Drill 23: Find the core line — Error handling patterns

Point to the line that does the main work and explain why.

Intermediate 5 min read Lesson 235 of 300 Challenge included
What you will be able to do
  • Point to the line that does the main work and explain why.

Practice task

Point to the line that does the main work and explain why.

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

Point to the line that does the main work and explain why.

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 235 of 300 · 0% of course