skip to content

The Question Mark Operator

? returns early on Err or None and converts the error with From on the way out. Interviewers ask what ? expands to and why it fails when the error types do not convert.

on this pageshow

questions

5

In Rust, what does the `?` operator do when applied to a `Result`, and how is that different from calling `unwrap`?

level: juniorimportance: must knowfreq 82%

answer

  1. early return, not a crash
  2. Ok yields the value
  3. Err leaves the function
  4. error passes through From::from

basics

~20 s

On Ok(v), the ? operator evaluates to v; on Err(e), it returns Err(From::from(e)) from the enclosing function at once. unwrap panics on Err instead, so ? hands a recoverable failure to the caller rather than crashing.

solid answer

~40 s

`expr?` on a `Result<T, E>` is an early-return shortcut. If the value is `Ok(v)`, the expression becomes `v` and execution continues. If it is `Err(e)`, the enclosing function returns `Err(From::from(e))` on the spot, so the error is converted into the function's own error type on the way out. That is why `?` only compiles inside a function or closure whose return type can receive it: a `Result` whose error type has a `From` impl for `E`. `unwrap` is different in kind: on `Err` it panics, which unwinds the thread (or aborts the process when the program is built with `panic = "abort"`). So `?` propagates a failure the caller is expected to handle, and `unwrap` asserts that the failure cannot happen.

code

rust · 22 lines
rust
use std::fs;
use std::num::ParseIntError;

// What `fs::read_to_string(path)?` and `parse()?` do, written out by hand.
fn read_port(path: &str) -> Result<u16, Box<dyn std::error::Error>> {
    let text = match fs::read_to_string(path) {
        Ok(t) => t,
        Err(e) => return Err(From::from(e)),
    };
    let parsed: Result<u16, ParseIntError> = text.trim().parse();
    let port = match parsed {
        Ok(p) => p,
        Err(e) => return Err(From::from(e)),
    };
    Ok(port)
}

fn main() {
    fs::write("server.conf", "8080\n").unwrap();
    println!("{:?}", read_port("server.conf"));
    println!("{:?}", read_port("absent.conf").is_err());
}

go deeper

for a junior

Recall the two outcomes: Ok yields the value, Err returns early from the function. Contrast it with unwrap, which panics instead of returning.

for a middle

Explain the expansion as a match that returns Err(From::from(e)), and why that return forces the enclosing function to have a compatible return type.

for a senior

Show you read every ? as a function exit: what has already happened before it, what the caller receives, and when an unwrap is a deliberate assertion instead.

for a principal

Frame ? as the point where a team's error types meet: every function boundary needs a From path, so the shape of error types decides how cheaply code composes.

## What `?` evaluates to In Rust, `?` is a postfix operator, written after an expression: `fs::read_to_string(path)?`. The Rust Reference calls it the **try propagation expression**; most people call it the question mark operator. Applied to a `Result<T, E>`, it does one of two things: - If the value is `Ok(v)`, the whole expression **evaluates to `v`**, typed as `T`, and the function carries on. - If the value is `Err(e)`, the enclosing function **returns immediately** with `Err(From::from(e))`. Nothing after that point in the function runs. The success path never touches `From`: only the error is converted. The Reference states the rule in exactly these terms: `Result::Ok(val)` evaluates to `val`, and `Result::Err(e)` returns `Result::Err(From::from(e))`. ## What it expands to For a `Result`, `?` behaves like a `match` you could write by hand: 1. Evaluate the expression to get a `Result<T, E>`. 2. On `Ok(v)`, produce `v` as the value of the expression. 3. On `Err(e)`, call `From::from(e)` to build the function's error type, wrap it in `Err`, and `return` it. ```rust let text = match fs::read_to_string(path) { Ok(t) => t, Err(e) => return Err(From::from(e)), }; ``` Internally the compiler drives `?` through two traits in `core::ops`, `Try` and `FromResidual`. Both are **unstable**, so your own types cannot implement them on stable Rust; what matters day to day is the `match` above. When the error type already equals the function's error type, the conversion is a no-op, because std implements `From<T> for T` for every type ("From (and thus Into) is reflexive", as the comment in `core::convert` puts it). ## Where `?` is allowed The `return` inside the expansion is the reason `?` has rules about placement: - The **innermost function or closure** must return a type that can accept the early return. For `?` on a `Result`, that is a `Result<U, F>` where `F: From<E>`. The success types `T` and `U` are unrelated: `?` on a `Result<String, io::Error>` works inside a function returning `Result<usize, io::Error>`. - In a function returning `()`, rustc rejects it with **E0277**: "the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)". The usual fix in `main` is to declare `fn main() -> Result<(), Box<dyn Error>>`. - `?` on an `Option` works in a function returning `Option`. On stable, `?` also applies to `ControlFlow` and, mostly in hand-written futures, to `Poll`-wrapped results. - `?` never converts between `Option` and `Result`; that takes an explicit `ok_or` or `ok`. ## `?` versus `unwrap` and `expect` | | `?` | `unwrap()` | `expect("msg")` | |---|---|---|---| | On `Ok(v)` | yields `v` | yields `v` | yields `v` | | On `Err(e)` | returns `Err(From::from(e))` | panics, showing `e` with `Debug` | panics with `msg` and `e` | | Caller sees | an `Err` value it can handle | a panic | a panic | | Needs a compatible return type | yes | no | no | A panic unwinds the current thread by default, running destructors, and aborts the whole process if the binary is built with `panic = "abort"`. Either way the caller gets no `Err` to inspect. That is the real difference: `?` keeps the failure **in the type system** as a value the caller must deal with; `unwrap` turns it into a crash with a message. ## A worked example: a CLI reading its config A command-line tool reads a config file and parses a port from it. Two different operations can fail with two different error types, `std::io::Error` and `std::num::ParseIntError`: ```rust fn read_port(path: &str) -> Result<u16, Box<dyn Error>> { let text = fs::read_to_string(path)?; // io::Error -> Box<dyn Error> let port: u16 = text.trim().parse()?; // ParseIntError -> Box<dyn Error> Ok(port) } ``` Each `?` is a possible exit. Both conversions work because std provides a blanket `From<E>` for `Box<dyn Error>` covering every type that implements `std::error::Error`. Had the function returned `Result<u16, io::Error>`, the second `?` would fail to compile, since there is no `From<ParseIntError>` for `io::Error`. ## What `?` does not do - It does **not** add context: the error that reaches the caller says what failed, not which file or step. Adding that context is a separate technique. - It does **not** log or print anything. - It does **not** catch panics; it only reacts to an `Err` (or `None`) value. - It does **not** retry or recover; the function simply stops at that point. Read every `?` as "if this failed, stop here and hand the failure, converted, to my caller".

  • Does `?` call `From::from` on the `Ok` value as well?
    No. Only the error path is converted. `Ok(v)` simply yields `v` with its original type `T`. The function's own success type is independent: `?` on a `Result<String, io::Error>` is fine inside a function returning `Result<usize, io::Error>`, because only `io::Error` has to convert into the function's error type.
  • What happens when the error type already matches the function's error type?
    `?` still calls `From::from`, but std implements `From<T> for T` for every type, and that impl returns its argument unchanged. So the conversion compiles to nothing, and the same `?` works whether or not a conversion is needed.
  • Can your own type support `?` the way `Result` and `Option` do?
    Not on stable Rust. `?` is driven by the `Try` and `FromResidual` traits in `core::ops`, which sit behind the unstable `try_trait_v2` feature, so user types cannot implement them. On stable, `?` works on `Result`, `Option`, `ControlFlow` and `Poll`-wrapped results; a custom type usually offers a method that returns a `Result` instead.

  • ? panics on Err exactly like unwrap, only with shorter syntax
  • ? can be used in any function, whatever that function returns
  • ? converts the Ok value into the function's success type too
  • ? turns a None into an Err automatically in a Result-returning function
  • Implementing the Try trait lets your own type use ? on stable Rust
open as a page

Why does rustc reject `text.trim().parse()?` with E0277 inside a Rust function returning `Result<u16, io::Error>`, and how do you fix it?

level: middleimportance: must knowfreq 68%

basics

~10 s

The ? operator converts the error with From::from, and std has no From<ParseIntError> for io::Error, so rustc reports E0277. Convert explicitly with map_err, or widen the error type, for example to Box<dyn Error>.

open as a page

What happens when a Rust program whose `main` is declared `fn main() -> Result<(), Box<dyn Error>>` returns an `Err` through `?`?

level: middleimportance: should knowfreq 58%

basics

~20 s

Through std's Termination impl for Result, the runtime prints Error: followed by the error's Debug form to stderr and exits with ExitCode::FAILURE, status 1 on Unix and Windows. Locals in main are dropped normally first; nothing panics.

open as a page

In Rust, why can't `?` be applied to an `Option` inside a function that returns `Result`, and how do you bridge the two?

level: middleimportance: should knowfreq 55%

basics

~10 s

The ? operator on an Option can only return None, which a Result-returning function cannot return, so rustc reports E0277. Bridge explicitly: ok_or or ok_or_else makes a Result, and ok() makes an Option.

open as a page

Inside a Rust closure, such as one passed to `Iterator::map`, why does `?` often fail to compile, and where does it return to when it does compile?

level: seniorimportance: should knowfreq 38%

basics

~20 s

The ? operator returns from the innermost closure, not the enclosing function, so the closure must return Result or Option. Otherwise rustc reports E0277; if the closure's error type cannot be inferred, E0282 until it is annotated.

open as a page