skip to content

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%

answer

  1. innermost function boundary
  2. the closure's own return type
  3. E0277 versus E0282
  4. annotate the closure's Result

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.

solid answer

~40 s

`?` desugars to an early `return`, and inside a closure that `return` leaves the closure. So in `lines.iter().map(|l| l.parse::<u16>()?)` the closure's body type is `u16`, and rustc reports E0277: the `?` operator can only be used in a closure that returns `Result` or `Option`. Even when the closure ends in `Ok(n)`, rustc often stops with E0282, type annotations needed, because `?` converts the error through `From`, which leaves the closure's error type open. Annotate it: `|s: &str| -> Result<u16, ParseIntError> { ... }`, or write `Ok::<_, ParseIntError>(n)`. When it compiles, a failing `?` returns `Err` from the closure only; the enclosing function keeps running and must handle that `Err`, for example by collecting into a `Result` or using `try_for_each`. A plain `for` loop avoids the issue, since there `?` returns from the function.

code

rust · 8 lines
rust
fn parse_ports(lines: &[&str]) -> Result<Vec<u16>, std::num::ParseIntError> {
    let ports = lines.iter().map(|l| l.trim().parse::<u16>()?).collect();
    Ok(ports)
}

fn main() {
    println!("{:?}", parse_ports(&["80", "443"]));
}

go deeper

for a junior

Recall that ? leaves the innermost closure or function, so a closure using ? must itself return a Result or an Option.

for a middle

Explain why E0277 appears when the closure returns a plain value, and why E0282 appears when a Result closure's error type is left to inference.

for a senior

Diagnose from the error code which boundary the ? hits, and pick the right restructuring: annotate the closure, collect the Results, use try_for_each, or switch to a loop.

for a principal

Favour code shapes where error flow is obvious to reviewers: loops or small typed helpers over dense closure chains whose Errs can be dropped without anyone noticing.

## `?` returns from the innermost function In Rust, `expr?` expands to a `match` whose failure arm executes `return`. A `return` always leaves the **innermost function-like body**: a function, a closure or an `async` block. So inside a closure, `?` returns from the closure, never from the function that contains it. Every rule below follows from that. ## Failure one: the closure does not return `Result` A CLI parses the port list from its config file: ```rust fn parse_ports(lines: &[&str]) -> Result<Vec<u16>, ParseIntError> { let ports = lines.iter().map(|l| l.trim().parse::<u16>()?).collect(); Ok(ports) } ``` The intention is "stop the whole function on the first bad line". But the `?` sits in the closure, and the closure's body evaluates to `u16`. rustc 1.99 reports **E0277**: "the `?` operator can only be used in a closure that returns `Result` or `Option` (or another type that implements `FromResidual`)", labelled "cannot use the `?` operator in a closure that returns `u16`". The enclosing function returning `Result` does not help, because the `?` cannot reach it. ## Failure two: the closure's error type cannot be inferred Make the closure return a `Result` and a different error appears: ```rust let parse = |s: &str| { let n: u16 = s.trim().parse()?; Ok(n) }; ``` rustc reports **E0282**, "type annotations needed", pointing at `Ok` and saying it "cannot infer type of the type parameter `E` declared on the enum `Result`". The reason is the conversion `?` performs: it returns `Err(From::from(e))`, and `From` can produce many types, so `ParseIntError` does not pin down the closure's error type. A function signature always states its return type; a closure usually leaves it to inference, and here inference has too little to go on. Two fixes, both naming the type once: 1. Annotate the closure: `|s: &str| -> Result<u16, ParseIntError> { ... }`. 2. Annotate the final value: `Ok::<u16, ParseIntError>(n)`, or `Ok::<_, ParseIntError>(n)`. ## Where the `Err` goes once it compiles With the annotation, a failing `?` produces an `Err` **from the closure**. The enclosing function sees an ordinary `Result` value and keeps running. In practice there are three ways to make the closure's failure stop the function: - **Use the result outside the closure.** Leave `?` out of `map`, then `collect` into `Result<Vec<u16>, ParseIntError>` and apply `?` there. Collecting results this way is covered with `Option` and `Result`. - **Use a short-circuiting adapter.** `Iterator::try_for_each` stops at the first `Err` the closure returns, and `?` on its result returns from the function. - **Use a `for` loop.** In a loop body there is no closure, so `?` returns from the function directly. This is often the clearest choice when the body has several fallible steps. ## Scoping `?` to a block Sometimes you want "try these three steps, and handle any failure here" without writing a helper function. Rust has an **unstable** `try` block for exactly that, but it is not available on stable 1.99. Stable code uses one of these instead: | Approach | Shape | Note | |---|---|---| | Helper function | `fn load(...) -> Result<_, E>` | clearest; the signature names the error type | | Immediately invoked closure | `(\|\| -> Result<_, E> { ... })()` | needs the return-type annotation | | `async` block, in async code | `async { ...; Ok::<_, E>(v) }` | `?` returns from the block's future, not the `async fn` | The `async` block behaves like a closure here: `?` inside it completes that block's future with the `Err`, and the same E0282 appears unless the error type is named. ## Diagnosing which problem you have - **E0277 mentioning a closure** means the closure's body type is not a `Result` or `Option`: change what the closure returns, or move the `?` outside it. - **E0282 on `Ok`** means the closure returns a `Result` whose error type `?` left open: annotate it. - **"couldn't convert the error"** means the annotated error type has no `From` impl for the source error, the same conversion failure as in a function. - **No error, but the function carries on after a bad input** means the `Err` came out of the closure and was ignored or collected somewhere unexpected.

  • How do you scope `?` to a few statements without a helper function on stable Rust?
    `try` blocks would do it but are unstable. On stable, use an immediately invoked closure with an annotated return type, `(|| -> Result<u16, ParseIntError> { let a: u16 = s.parse()?; Ok(a) })()`, so a failing `?` ends only that closure. A small named helper function is often clearer, because its signature states the error type.
  • Does `?` inside an `async` block return from the enclosing `async fn`?
    No. An `async` block is its own boundary, like a closure: `?` completes the block's future with the `Err`, and the surrounding code receives it when it awaits the block. The block's error type often needs naming, for example by ending it with `Ok::<_, ParseIntError>(n)`, for the same inference reason as closures.

  • ? inside a closure returns from the function that contains the closure
  • ? can never be used inside a closure at all
  • E0282 is fixed by a turbofish on parse rather than on the Result
  • try blocks are stable and the normal way to scope ?
  • If the enclosing function returns Result, ? in map is fine