0Pricing
Learn Rust Coding · Lesson

Result and the ? Operator

Propagate errors.

Result and the ? Operator is a free Learn Rust Coding lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The Result Type

Result<T, E> represents an operation that can succeed with Ok(T) or fail with Err(E). It is Rust's primary error-handling type.

fn main() {
    let parsed: Result<i32, _> = "42".parse::<i32>();
    println!("{:?}", parsed);
}

Matching on Result

You can handle both outcomes explicitly with match.

fn main() {
    match "oops".parse::<i32>() {
        Ok(n) => println!("got {n}"),
        Err(e) => println!("error: {e}"),
    }
}

Returning Result

Functions that can fail return a Result, letting the caller decide how to handle errors.

fn halve(n: i32) -> Result<i32, String> {
    if n % 2 == 0 {
        Ok(n / 2)
    } else {
        Err("odd number".to_string())
    }
}

fn main() {
    println!("{:?}", halve(10));
    println!("{:?}", halve(7));
}

The ? Operator

The ? operator unwraps an Ok value or returns the Err early from the function. It replaces verbose match-and-return code.

fn double_str(s: &str) -> Result<i32, std::num::ParseIntError> {
    let n = s.parse::<i32>()?;
    Ok(n * 2)
}

fn main() {
    println!("{:?}", double_str("21"));
    println!("{:?}", double_str("x"));
}

Chaining with ?

Multiple fallible steps read cleanly when chained with ?; the first error short-circuits the rest.

fn sum_two(a: &str, b: &str) -> Result<i32, std::num::ParseIntError> {
    let x = a.parse::<i32>()?;
    let y = b.parse::<i32>()?;
    Ok(x + y)
}

fn main() {
    println!("{:?}", sum_two("3", "4"));
}

? in main

main can return Result, so ? works there too. A returned Err ends the program with a non-zero exit code.

fn main() -> Result<(), std::num::ParseIntError> {
    let n: i32 = "100".parse()?;
    println!("parsed {n}");
    Ok(())
}

Useful Result Methods

Handy combinators:

  • unwrap_or(default) — value or a fallback
  • map — transform the Ok value
  • map_err — transform the error
  • is_ok / is_err — check the variant
fn main() {
    let n = "x".parse::<i32>().unwrap_or(-1);
    println!("{n}");
}

Option to Result

Convert an Option into a Result with ok_or so ? can propagate a meaningful error.

fn first_char(s: &str) -> Result<char, String> {
    let c = s.chars().next().ok_or("empty string".to_string())?;
    Ok(c)
}

fn main() {
    println!("{:?}", first_char("hi"));
    println!("{:?}", first_char(""));
}

How ? Converts Errors

When the error types differ, ? calls From::from to convert the error into the function's declared error type. This powers ergonomic error handling across layers.

Avoid unwrap in Production

unwrap and expect panic on Err. They are fine for examples and tests, but prefer ? or explicit handling in real code so failures stay recoverable.

Chaining and_then

and_then runs the next fallible step only if the previous one succeeded, threading the value through.

fn main() {
    let result = "8"
        .parse::<i32>()
        .and_then(|n| Ok(n * 2));
    println!("{:?}", result);
}

Quick Check

What does the ? operator do when applied to a Result that is Err?

Recap

You learned Result-based error handling:

  • Result<T, E> models success or failure
  • ? unwraps Ok or returns Err early
  • ? works in functions and main that return Result
  • Combinators like map, map_err, unwrap_or, and ok_or help
  • Avoid unwrap in production

Frequently asked questions

Is the “Result and the ? Operator” lesson free?

Yes — the full text of “Result and the ? Operator” is free to read here on the web, and the Learn Rust Coding course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.

What will I learn in “Result and the ? Operator”?

Propagate errors. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Learn Rust Coding?

No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Result and the ? Operator” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Learn Rust Coding lesson?

Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Result and the ? Operator
  2. thiserror
  3. anyhow
  4. Error Conversion
← Back to Learn Rust Coding