Rust

Lesson 04

Option instead of unwrap

Keep missing data in Option until the boundary decides the fallback or rejection path.

Good Code

src/review_score.rs
pub fn reviewer_score(reviews: &[Review], reviewer_id: u64) -> Option<u8> {
    // The caller decides what a missing reviewer means for the request.
    reviews
        .iter()
        .find(|review| review.reviewer_id == reviewer_id)
        .map(|review| review.score)
}

Bad Code

review_score.rs
pub fn reviewer_score(reviews: &[Review], reviewer_id: u64) -> u8 {
    // unwrap hides the missing-review branch inside a helper.
    reviews
        .iter()
        .find(|review| review.reviewer_id == reviewer_id)
        .unwrap()
        .score
}

Review Notes

What to review

Good Code

The good version returns Option<u8>, so the caller can return a default, produce a validation error, or keep the field absent.

Bad Code

The bad version assumes the reviewer exists. A normal miss path becomes a panic far away from the HTTP, CLI, or job boundary that should choose the response.

Takeaways

  • A Rust lookup that can miss should keep the miss path visible instead of unwrapping inside helper code.