C.W.K.
Stream
Lesson 06 of 06 · published

A Glimpse of Result

~9 min · enums, result, errors

Level 0Rust Curious
0 XP0/80 lessons0/19 achievements
0/100 XP to next level100 XP to go0% complete

You've met Option, the enum for 'maybe a value.' Its sibling is Result, the enum for 'maybe an error.' Meeting it now — as just another enum — makes the entire Error Handling track feel like home.

Result is Option's cousin

Result<T, E> has two variants: Ok(T) (success, carrying the value) and Err(E) (failure, carrying an error). Where Option says 'present or absent,' Result says 'succeeded or failed, and here's why it failed.' That extra E — the reason — is the whole difference.

You handle it the same way

Because it's an enum, you handle Result with the tools you just learned: match on Ok and Err, or if let Ok(v), or methods like unwrap_or. Anything that can fail — parsing a number, reading a file, opening a socket — returns a Result, and the compiler makes you confront the Err case.

Errors are values, not exceptions. Rust has no try/catch and no thrown exceptions. A function that can fail says so in its return type (Result), and failure flows through your code as an ordinary value you match on. You can't accidentally ignore an error you never see — the type is right there in the signature.

The bridge to the next track

Returning Result everywhere could get verbose — match, match, match. The Error Handling track introduces the ? operator that makes error propagation a single character, plus how to define your own error types. You already understand the enum; now you'll learn to wield it ergonomically.

Code

Result: success or a reason for failure·rust
fn parse_age(s: &str) -> Result<u32, String> {
    match s.trim().parse::<u32>() {
        Ok(n) => Ok(n),
        Err(_) => Err(format!("not a number: {s}")),
    }
}

fn main() {
    match parse_age("42") {
        Ok(age) => println!("age is {age}"),
        Err(e) => println!("error: {e}"),
    }
    // Result is an enum, so Option-style methods work too:
    let age = parse_age("oops").unwrap_or(0);
    println!("fallback age: {age}");
}

External links

Exercise

Write fn divide(a: f64, b: f64) -> Result<f64, String> that returns Err with a message when dividing by zero, and Ok otherwise. Handle both with a match. Then predict: in the next track, what would replace that match when you just want to propagate the error upward?
Hint
The ? operator. It returns the Err early and unwraps the Ok, turning a three-line match into one character — the headline feature of the Error Handling track.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue
💛 by Ttoriwarm

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.