Email me

Rust errors / Patterns and matching

Rust compiler error · checked with rustc 1.99.0

Rust error E0510: cannot assign `x` in match guard

What it meansThe matched value was assigned in a match guard.

What rustc prints

error[E0510]: cannot assign `x` in match guard
 --> main.rs:6:18
  |
4 | match x {
  |       - value is immutable in match guard
5 |     None => {}
6 |     Some(_) if { x = None; false } => {} // error!
  |                  ^^^^^^^^ cannot assign

Real output of rustc 1.99.0 compiling the official example below (2021 edition). Your names and line numbers will differ; the first line is the part to match.

E0510Patterns and matching
Activein rustc 1.99.0
5related errors linked below

The compiler team's explanation

The matched value was assigned in a match guard.

Erroneous code example:

let mut x = Some(0);
match x {
    None => {}
    Some(_) if { x = None; false } => {} // error!
    Some(_) => {}
}

When matching on a variable it cannot be mutated in the match guards, as this could cause the match to be non-exhaustive.

Here executing x = None would modify the value being matched and require us to go "back in time" to the None arm. To fix it, change the value in the match arm:

let mut x = Some(0);
match x {
    None => {}
    Some(_) => {
        x = None; // ok!
    }
}

From rustc --explain E0510 (1.99.0), part of the Rust project, MIT or Apache-2.0. Official page.

Related errors

All 518 Rust error codes · Rust crate data · Glossary

Up next

Often hit nextE0004: non-exhaustive patternsA related error from the same family.Read it next →

Did this answer your question?

Get the receipts by email.

What my AI agents tried this week, with the real numbers: what worked, what flopped, what made money. One email when there is something worth reading.

No spam, never sold. Every email has a one-click unsubscribe.

Popular in the shop

All 124 tools →

Browse: Bundles and kitsHome, family and schoolMoney and businessAI toolsSports and fitnessMaking and hobbiesFood and drinkIndie dev and launchTrading and quant

Free: Landing page teardown iPhone app cost calculator LLM API cost calculator Paid online: $49 Launch Check App builds Articles FAQ