---
title: "Option, Result and the ? operator in Rust"
slug: "option-result-and-question-mark"
description: "Handle a missing value with Option and a failing call with Result, and pass errors up with the ? operator. Fix ? used in a main that returns nothing."
published: "2026-12-03"
updated: "2026-12-03"
canonical: "https://aifree.dev/courses/learn-rust/option-result-and-question-mark"
---

# Option, Result and the ? operator in Rust

How does Rust handle a value that may be missing or an operation that may fail?

## Predict

```rust
fn main() {
    for text in ["42", "x"] {
        match text.parse::<i32>() {
            Ok(n) => println!("number {n}"),
            Err(_) => println!("not a number"),
        }
    }
}
```

What does this program print?

- number 42, then number 0
- number 42, then not a number
- It does not compile because parse can fail

Answer: number 42, then not a number — The first text parses to Ok(42). "x" gives an Err, so the second arm runs.

Output:

```
number 42
not a number
```

`parse` returns a `Result`. `Ok(n)` carries the number, and `Err(_)` means the text was not one.

## No null, no exceptions

Rust has no null and no exceptions. A value that may be missing is an `Option<T>`: `Some(value)` or `None`. An operation that may fail returns a `Result<T, E>`: `Ok(value)` or `Err(error)`. Both are ordinary enums, so `match` works on them. The compiler makes you handle both cases before you can use the value inside.

## Working with Option

```rust
fn first_word(text: &str) -> Option<&str> {
    text.split_whitespace().next()
}

fn main() {
    if let Some(word) = first_word("hello brave world") {
        println!("first word: {word}");
    }
    let empty = first_word("   ");
    println!("{}", empty.unwrap_or("nothing"));
    let length = first_word("rust").map(|w| w.len());
    println!("{length:?}");
}
```

Output:

```
first word: hello
nothing
Some(4)
```

`next()` gives `None` when there is no word. `if let` runs only for `Some`, `unwrap_or` supplies a default and `map` changes the value inside a `Some`.

Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=1c09f5d6399a5b0c35ae414cf5f64ac2

## The ? operator

Inside a function that returns `Result`, `?` after a call does two things. On `Ok(v)` it gives you `v`. On `Err(e)` it returns that error from your function at once. In a function that returns `Option`, it returns `None` the same way. `unwrap` and `expect` panic on the bad case instead. They are fine for experiments, not for real programs.

## Passing errors up with ?

```rust
use std::num::ParseIntError;

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

fn main() {
    println!("{:?}", total("20", "22"));
    match total("20", "abc") {
        Ok(sum) => println!("sum {sum}"),
        Err(e) => println!("error: {e}"),
    }
}
```

Output:

```
Ok(42)
error: invalid digit found in string
```

The first `?` passes up the error of `a`, the second the error of `b`. `main` decides what to do with it: `{:?}` prints the whole `Result`, and the `match` prints a message.

Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=39730f24d0cd584912cb798f119579cf

## Fix it

```rust
fn main() {
    let n: i32 = "42".parse()?;
    println!("{n}");
}
```

This program does not compile. What is the bug?

- parse needs a turbofish: parse::<i32>()
- The string "42" is not a valid number
- main returns (), so ? has nowhere to send the error

Answer: main returns (), so ? has nowhere to send the error — Make main return a Result and end it with Ok(()).

Compiler message:

```
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
```

Fixed:

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

Output:

```
42
```

## Say it back

In your own words: what does the ? operator do?

Our sentence: On Ok it unwraps the value and carries on. On Err it returns that error from the current function right away, so the caller decides what to do.

## Mission (10 min)

Write a program with a list of two &str values. Parse both as numbers with ?, and print their sum or the error. Try "7" and "8", then "7" and "x".

```sh
cargo new parse-sum
cd parse-sum
cargo run
```

## Common questions

### What is the difference between Option and Result in Rust?

Option<T> is for a value that may be missing: it is Some(value) or None. Result<T, E> is for an operation that may fail: it is Ok(value) or Err(error). Use Option when absence is normal and needs no reason, and Result when you want to say what went wrong.

### What does the ? operator do in Rust?

The ? operator goes after an expression that returns a Result or an Option. If it holds a good value, you get that value. If it holds an error or None, the function returns early with it. So the function must itself return a compatible Result or Option, or the code does not compile.

### When should I use unwrap in Rust?

unwrap and expect return the value, but they panic and stop the program on Err or None. They are fine in quick experiments, in tests, and when you can prove the value is there. In real code, prefer match, if let, unwrap_or or the ? operator, so bad input is handled instead of crashing the program.

## Sources

- https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html (read 2026-12-03)
- https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html (read 2026-12-03)
- https://doc.rust-lang.org/std/option/enum.Option.html (read 2026-12-03)

Measured with rustc 1.100.1 (play.rust-lang.org, stable, edition 2024) on 2026-12-03.
