skip to content

In Rust, what does `if let Some(header) = req.auth && let Some(token) = header.strip_prefix("Bearer ")` allow, and why does it fail on edition 2021?

level: seniorimportance: should knowfreq 35%

answer

  1. several lets joined by &&
  2. left to right, short-circuit
  3. bindings flow rightward
  4. 2024 edition only, Rust 1.88

basics

~20 s

A let chain joins let patterns and bool tests with && in one if or while condition, each binding visible to later operands. It is stable since Rust 1.88 on the 2024 edition only, so edition 2021 rejects it.

solid answer

~40 s

A let chain puts several `let` patterns and ordinary `bool` expressions in one `if` or `while` condition, separated by `&&`. Operands run left to right and stop at the first `false` or failed match; each pattern's bindings are in scope for the operands after it and for the then-block, but not for the `else`. So `header` from the first `let` feeds the second, and `token` can then be tested and parsed, all without nesting. Let chains were stabilised in Rust 1.88 for the 2024 edition only, because they rely on the 2024 change to `if let` temporary scopes. A crate on edition 2021 gets `let chains are only allowed in Rust 2024 or later`, with no error code. Mixing `||` into the chain is rejected too; parenthesise a boolean sub-expression instead.

code

rust · 23 lines
rust
struct Request<'a> {
    auth: Option<&'a str>,
}

fn user_id(req: &Request) -> Option<u32> {
    // Rust 2024 let chain: each `let` binds for the operands to its right.
    if let Some(header) = req.auth
        && let Some(token) = header.strip_prefix("Bearer ")
        && !token.is_empty()
        && let Ok(id) = token.parse::<u32>()
    {
        Some(id)
    } else {
        None
    }
}

fn main() {
    let ok = Request { auth: Some("Bearer 42") };
    let bad = Request { auth: Some("Basic abc") };
    let none = Request { auth: None };
    println!("{:?} {:?} {:?}", user_id(&ok), user_id(&bad), user_id(&none));
}

go deeper

for a junior

Read a let chain as nested if lets flattened with &&, and know that it needs the 2024 edition.

for a middle

Explain left-to-right short-circuit evaluation, how bindings flow to later operands but not to else, and the rule against top-level ||.

for a senior

State that chains are 2024-only since Rust 1.88, why a library's minimum Rust version matters, and why a failing operand ends a whole while loop.

for a principal

Weigh adopting let chains against a crate's supported Rust versions and edition plan, and set guidance for when a chain should become a function.

## What a let chain is Before the 2024 edition, `let` could appear in a condition only as the whole condition: `if let PAT = EXPR` or `while let PAT = EXPR`. Testing two patterns meant nesting: ```rust if let Some(header) = req.auth { if let Some(token) = header.strip_prefix("Bearer ") { if !token.is_empty() { /* ... */ } } } ``` A **let chain** flattens this. The condition of an `if` or `while` becomes a sequence of operands joined by `&&`, where each operand is either a `bool` expression or a `let PATTERN = SCRUTINEE`. The edition guide describes it as allowing *chaining of `let` expressions inside `if` and `while` condition operands*. ## Evaluation and scope rules The Reference spells out the behaviour: - **Left to right, short-circuiting.** Like `&&` on booleans, *each operand is evaluated from left-to-right until an operand evaluates as false or a let match fails*; later operands are not evaluated. - **Bindings flow rightward.** *The bindings of each pattern are put into scope to be available for the next condition operand and the consequent block.* They are not visible in the `else` block, where using one is E0425. - **No top-level `||`.** *If any condition operand is a let pattern, then none of the condition operands can be a `||` lazy boolean operator expression.* rustc reports `` `||` operators are not supported in let chain conditions ``; wrap the boolean part in parentheses: `&& (admin || force)`. - **`let` must sit at the top level of the chain**, so `if (let Some(a) = x || let Some(a) = y)` is not allowed. - **`while` accepts the same chains**, with the same rules. ## Why it depends on the edition Let chains were stabilised in **Rust 1.88** and only for crates on the **2024 edition**. The edition guide gives the reason: the feature *requires `if let` rescoping*, the 2024 change to when temporaries in an `if let` scrutinee are dropped, which the material on the 2024 edition covers. On edition 2021, rustc 1.99 still rejects every `let` in the chain with `let chains are only allowed in Rust 2024 or later`. That message carries no error code. The edition guide notes that no migration is needed, because chains only add newly valid programs. Two version facts follow for anyone maintaining a library: 1. The edition is set per crate, with `edition = "2024"` in Cargo.toml; the per-crate edition material covers how crates on different editions interoperate. 2. The 2024 edition shipped in Rust 1.85, but let chains arrived in 1.88. A crate that must still build with Rust 1.85, 1.86 or 1.87 cannot use them, even on the 2024 edition: those compilers accept the edition but not the chains. ## Before 2024, and the alternatives | Approach | Later test can use an earlier binding? | Short-circuits? | Notes | |---|---|---|---| | Let chain (2024) | yes | yes | flat; `else` runs on any failure | | Nested `if let` | yes | yes | indents; one `else` per level | | Tuple pattern `if let (Some(a), Some(b)) = (x, y)` | no | no: both computed first | only for independent values | | `let`-`else` guards | yes | yes | fits early returns, not a two-branch `if` | | `Option` combinators such as `and_then` | yes | yes | the `Option` material covers them | ## Chains in `while` loops A chain in `while` ends the **whole loop** at the first failing operand. With `while let Some(slot) = queue.pop() && let Some(v) = slot`, popping a `None` slot stops the loop even if more items remain; it does not skip that slot. To skip, put a `let`-`else` with `continue` or an `if let` inside a plain `while let` body. ## When to use them - **Guard sequences that build on each other**: header, then prefix, then non-empty, then parse. - **Conditions mixing patterns and plain tests**: `if let Some(user) = session && user.is_admin()`. - **Not as a replacement for `match`** over several variants; a long chain is a sign to extract a function.

  • Why does `if let Some(x) = a && x > 0 || force { ... }` fail in Rust 2024?
    A condition that contains a `let` cannot also use `||` at the top level, because the precedence against the scrutinee would be ambiguous; rustc reports `` `||` operators are not supported in let chain conditions ``. Parenthesise the boolean part, `&& (x > 0 || force)`, or restructure if `force` alone should enter the block.
  • What happens to `while let Some(slot) = queue.pop() && let Some(v) = slot` when it pops a `None` slot?
    The loop ends. A failed operand ends the whole `while`, not just that iteration, so later items are never popped. To skip empty slots, loop on `while let Some(slot) = queue.pop()` and use `let Some(v) = slot else { continue };` inside.
  • How was the same check written before the 2024 edition?
    With nested `if let` blocks, or with `Option::and_then` chains. A tuple pattern such as `if let (Some(a), Some(b)) = (x, y)` works only when the values are independent, because both are computed first and the second cannot use the first's binding.

  • let chains work on every edition once the compiler is 1.88 or newer
  • bindings from a let chain are also available in the else block
  • you can freely mix || and && in a condition that contains let
  • a failed let in a while chain skips that iteration and keeps looping
  • a tuple pattern if let (Some(a), Some(b)) is an exact pre-2024 equivalent

Assumes Rust 1.99 on edition 2024; let chains are stable since Rust 1.88 and only on the 2024 edition.