Loading
0xC0Lesson 13 of 17

Result propagation and the ? operator

Handle fallible steps clearly with `Result` and `?`.

18 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • Use ? to propagate parsing and validation errors.

The ? operator short-circuits on Err and unwraps Ok values, making fallible code concise. It works in functions that return Result (or compatible types) and keeps error flow explicit.

main.rs
1fn parse_positive(value: &str) -> Result<i32, String> {
2    let number: i32 = value.trim().parse().map_err(|_| "invalid integer".to_string())?;
3    if number > 0 { Ok(number) } else { Err("must be positive".to_string()) }
4}
5
6fn main() {
7    println!("{:?}", parse_positive("12"));
8}
Output
Ok(12)

Use ? for each fallible step to return early on failure. This keeps the happy path readable while preserving explicit error handling.

Try it

Up to 15 XP

Trace `?` through a fallible workflow

Follow how ? either continues with Ok or returns early with Err.

Message 1 of 3Predicted 0/0
Input text
parse helper
caller handling

Key takeaways

  • Use ? to propagate parsing and validation errors.

  • Rust uses types and ownership rules to prevent common bugs.

  • Small experiments build intuition quickly.

Lesson quiz

5 questions · pass with 4 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write Rust

These run for real. Write the program, press Run tests, and read what the compiler tells you - learning to read compiler messages is half of learning Rust.

Exercise 1

Divide with propagated errors

+25 XP

Implement safe_divide returning Result<i32, String>. Return an error for division by zero; otherwise return quotient. Print value or error.

  • Valid division
  • Division by zero
main.rs
Loading editor…

Rust lessons are authored for modern stable Rust; exercises run on Rust 1.82 via Wandbox, a free public service. Your source code and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…