Rust

E0510 Cannot Assign in Match Guard Fix

This error is never about the arm that follows the guard. The guard runs while the compiler is still deciding whether the pattern matches at all, and during that decision the matched value is read-only — assigning to it inside the guard is refused with E0510, even though the variable is declared mut. Move the assignment into the arm body, settle the condition before the match begins, or replace the match with an if let, and the same program compiles unchanged in every other respect.

Written November 27, 2026 · Tested with Rust 1.99.1 · 18 min read

By the end of this guide
  • The error: assigning the matched value inside its own guard
  • First fix: move the assignment into the arm body
  • Second fix: decide before the match
  • Third fix: drop the match for an if let

Written November 27, 2026

Tested with Rust 1.99.1

What this guide is

A match guard is the if condition after a pattern, and it runs at an awkward moment: the pattern has matched, but the compiler has not yet committed to the arm. If the guard returns false, matching continues with the next arm, against the same value. That is why the value being matched has to stay fixed while the guard runs. A guard that assigns to that value — state = None tucked inside a guard block, usually as a side effect on the way to returning a boolean — would change the very thing the remaining arms are about to be tested against. E0510 is the compiler refusing that assignment: the matched value was assigned in a match guard.

The refusal surprises people because the variable is usually declared mut, and assignments to it are legal everywhere else in the function — before the match, inside every arm body, and after the match ends. The one place they are not legal is inside a guard of a match on that same value. Every repair below respects that boundary rather than fighting it: the assignment moves a few lines, into the arm the guard was guarding, or the decision the guard was making gets settled before the match starts, or the match goes away in favor of an if let whose body has no such restriction. The guarded logic itself — what gets cleared, and when — stays exactly the same.

The error: assigning the matched value inside its own guard

This program holds an optional port number. The middle arm tries to clear state from inside its guard and then return false, so matching would fall through to the last arm:

Rust
fn main() {
    let mut state = Some(8080);
    match state {
        None => println!("no port set"),
        Some(_) if { state = None; false } => println!("resetting"),
        Some(port) => println!("port = {}", port),
    }
}
Terminal
$ rustc --edition 2021 main.rs -o main.bin
error[E0510]: cannot assign `state` in match guard
 --> main.rs:5:22
  |
3 |     match state {
  |           ----- value is immutable in match guard
4 |         None => println!("no port set"),
5 |         Some(_) if { state = None; false } => println!("resetting"),
  |                      ^^^^^^^^^^^^ cannot assign

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0510`.

Two spans carry the diagnosis. The scrutinee line, match state, is underlined with the note value is immutable in match guard — for the duration of any guard in this match, state is treated as immutable, whatever its declaration says. The assignment span inside the guard is marked cannot assign, and the header names the place and the context: cannot assign state in match guard. There is no suggestion to add mut; state already has it, at line 2. The problem is not the declaration. It is the location of the assignment, inside a guard, while the match is still undecided.

Notice also what the guard was trying to do semantically. It clears the value and returns false, expecting the Some(port) arm below to run next. But if the assignment had been allowed, that arm would have been tested against None, not against the Some(8080) the pattern just matched — the match would need to start over from the top, including the None arm it already passed. The ban is what keeps a match a single forward pass over one fixed value.

First fix: move the assignment into the arm body

The repair the compiler's own documentation gives for this error is to change the value in the match arm instead of in the guard. Once an arm is chosen, the decision is final, and the arm body may assign to the matched variable freely. Here the guarded arm disappears: the Some arm itself clears state after reading the port out of it:

Rust
fn main() {
    let mut state = Some(8080);
    match state {
        None => println!("no port set"),
        Some(port) => {
            state = None;
            println!("port = {} cleared", port);
        }
    }
    println!("after: {:?}", state);
}
Terminal
$ rustc --edition 2021 main.rs -o main.bin
$ ./main.bin
port = 8080 cleared
after: None

The program prints port = 8080 cleared and then after: None, and exits with status 0. The assignment state = None is character-for-character the one the guard tried to run; it compiles here because it sits in an arm body, after the match has committed. The pattern binding port is copied out of the value first, so clearing state afterward cannot disturb the value the arm is printing. This is the right default repair: most guards that assign were never really conditions — they were arm bodies that drifted left of the =>.

Second fix: decide before the match

Sometimes the guard is a real condition, and the assignment is a consequence that should happen only when the condition holds. Then split the two. Compute the condition before the match, from values the match is not testing, and let the guard do nothing but read that precomputed flag. The assignment stays behind the guard, in the arm:

Rust
fn main() {
    let mut state = Some(8080);
    let reset_requested = true;
    match state {
        None => println!("no port set"),
        Some(_) if reset_requested => {
            state = None;
            println!("port cleared");
        }
        Some(port) => println!("port = {}", port),
    }
    println!("after: {:?}", state);
}
Terminal
$ rustc --edition 2021 main.rs -o main.bin
$ ./main.bin
port cleared
after: None

The program prints port cleared and after: None, and exits with status 0. The guard if reset_requested only reads a boolean that was settled before the match began, so nothing the guard depends on can change while matching runs. The assignment runs in the arm body, where assignments are legal. Reach for this shape when the original guard was reading outside state — a flag, a configuration value, a request field — and acting on the matched value in the same breath. The reading moves before the match; the acting stays in the arm.

Third fix: drop the match for an if let

When the match has only two real outcomes — the value is present, or it is not — the match itself may be more machinery than the job needs. An if let has no guards at all, so there is no guard context for the assignment to fall foul of; its body is ordinary code, and assigning to the variable that was just tested is legal there:

Rust
fn main() {
    let mut state = Some(8080);
    if let Some(port) = state {
        state = None;
        println!("port = {} cleared", port);
    } else {
        println!("no port set");
    }
    println!("after: {:?}", state);
}
Terminal
$ rustc --edition 2021 main.rs -o main.bin
$ ./main.bin
port = 8080 cleared
after: None

The program prints port = 8080 cleared and after: None, and exits with status 0 — the same behavior as the first fix, reached by removing the construct that imposed the restriction instead of rearranging code inside it. This is the right repair when the guarded match was a two-case test wearing a three-arm costume. It is the wrong repair for a match with several patterns and several guards; there, moving assignments into arms keeps the structure that made the code readable.

The ban follows the matched place: matching on a struct field

The restriction is not tied to a variable name. It follows whatever place expression the match is testing. Matching on a field, config.port, makes that field the matched value, and a guard that assigns to the same field fails with the same code and the same wording, naming the full place:

Rust
struct Config {
    port: Option<u16>,
}

fn main() {
    let mut config = Config { port: Some(8080) };
    match config.port {
        None => println!("no port set"),
        Some(_) if { config.port = None; false } => println!("resetting"),
        Some(port) => println!("port = {}", port),
    }
}
Terminal
$ rustc --edition 2021 main.rs -o main.bin
error[E0510]: cannot assign `config.port` in match guard
 --> main.rs:9:22
  |
7 |     match config.port {
  |           ----------- value is immutable in match guard
8 |         None => println!("no port set"),
9 |         Some(_) if { config.port = None; false } => println!("resetting"),
  |                      ^^^^^^^^^^^^^^^^^^ cannot assign

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0510`.

The header now reads cannot assign config.port in match guard, and the scrutinee underline sits under match config.port. Nothing about config being a struct changes the rule, and the repairs are the same ones: clear the field in the arm body that needs it cleared, not in that arm's guard. What this case settles is the scope of the ban — it is the matched place, in whatever form the scrutinee takes, that is immutable in a guard. A guard in this match could still assign to a different field of config or to an unrelated variable; it is config.port itself that is off limits.

A guard may assign other variables

The ban is narrower than it first looks. A guard that assigns to a different mutable variable — one the match is not testing — compiles and runs. Here the guard keeps a count of how many times it was evaluated, in a variable that has nothing to do with the matched value:

Rust
fn main() {
    let mut seen = 0;
    let state = Some(8080);
    match state {
        None => println!("no port set"),
        Some(port) if { seen += 1; port > 1024 } => {
            println!("port = {} seen = {}", port, seen)
        }
        Some(port) => println!("small port = {}", port),
    }
}
Terminal
$ rustc --edition 2021 main.rs -o main.bin
$ ./main.bin
port = 8080 seen = 1

The program prints port = 8080 seen = 1 and exits with status 0. The guard block runs seen += 1 and then evaluates the comparison that is its actual condition. So a block-bodied guard is not restricted to pure expressions, and side effects in guards are not banned as a class. The one assignment that is banned is the assignment to the matched place itself. That distinction matters when you meet E0510 in real code: the fix is not to strip the guard of every effect, it is to find the one assignment whose target is the scrutinee and move that one into the arm.

Interior mutability is not a fix: the Cell case

There is one way to change the underlying value from inside a guard that the compiler accepts, and it is worth seeing precisely because it is a trap rather than a repair. When the matched value is a copy produced by a method call — here, state.get() on a Cell — the scrutinee is that copy, not the cell. A guard can call state.set(None), which mutates through a shared reference, and no assignment to the matched place ever appears:

Rust
use std::cell::Cell;

fn main() {
    let state = Cell::new(Some(8080));
    match state.get() {
        None => println!("no port set"),
        Some(_) if { state.set(None); false } => println!("resetting"),
        Some(port) => println!("port = {}", port),
    }
    println!("after: {:?}", state.get());
}
Terminal
$ rustc --edition 2021 main.rs -o main.bin
$ ./main.bin
port = 8080
after: None

The program prints port = 8080 and after: None, and exits with status 0. Read that output carefully. The guard ran state.set(None), then returned false, so the guarded arm was never taken — matching fell through to the plain Some(port) arm, which printed the port from the copy it had already made. Yet the cell still ends up None. The side effect happened even though the guard failed and its arm was skipped. A guard is a test that may be run and then discarded; anything it changes through interior mutability stays changed. Do not use this shape to work around E0510. If a value must change, change it in an arm, where the change is tied to a decision the match actually made.

Neighboring errors: the binding, and the plain immutable variable

Two nearby mistakes look like E0510 in the editor and are reported under different codes, because different rules are doing the refusing.

Assigning to a variable bound by the pattern itself — the port in Some(port) — inside that arm's guard is E0594, not E0510:

Rust
fn main() {
    let state = Some(8080);
    match state {
        None => println!("no port set"),
        Some(port) if { port = 0; false } => println!("zeroed"),
        Some(port) => println!("port = {}", port),
    }
}
Terminal
$ rustc --edition 2021 main.rs -o main.bin
error[E0594]: cannot assign to `port`, as it is immutable for the pattern guard
 --> main.rs:5:25
  |
5 |         Some(port) if { port = 0; false } => println!("zeroed"),
  |                         ^^^^^^^^ cannot assign
  |
  = note: variables bound in patterns are immutable until the end of the pattern guard

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0594`.

The header says the binding is immutable for the pattern guard, and the note under the span gives the duration: variables bound in patterns are immutable until the end of the pattern guard. This is a separate restriction from E0510's. E0510 protects the scrutinee place; E0594 protects the pattern's own bindings while the guard runs. Both restrictions lift when the arm body starts — the binding becomes usable there, and the matched value assignable — but they are diagnosed separately, and a mut on the binding does not turn the guard case into legal code either; the immutability is imposed by the guard context, not by the binding's declaration. One condition survives into the arm: assigning to the binding itself inside the arm body still needs the binding declared mut, as in Some(mut port). Without that mut, the arm-body assignment is refused with E0384, the ordinary immutable-variable error — the move past the guard and the mut are separate requirements, and the binding case needs both.

Assigning to an ordinary immutable variable in a guard — one that is neither the scrutinee nor a pattern binding — is just the everyday immutable-assignment error, E0384, with nothing guard-specific about it:

Rust
fn main() {
    let state = Some(8080);
    let note = 1;
    match state {
        None => println!("no port set"),
        Some(_) if { note = 2; false } => println!("noted"),
        Some(port) => println!("port = {}", port),
    }
    let _ = note;
}
Terminal
$ rustc --edition 2021 main.rs -o main.bin
error[E0384]: cannot assign twice to immutable variable `note`
 --> main.rs:6:22
  |
3 |     let note = 1;
  |         ---- first assignment to `note`
...
6 |         Some(_) if { note = 2; false } => println!("noted"),
  |                      ^^^^^^^^ cannot assign twice to immutable variable
  |
help: consider making this binding mutable
  |
3 |     let mut note = 1;
  |         +++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0384`.

Here note was never declared mut, and the compiler says so in the usual way, pointing back at the first assignment and suggesting let mut note. Compare the three codes side by side and the map is complete: assigning the matched place in a guard is E0510, assigning a pattern binding in a guard is E0594, and assigning an immutable variable anywhere, guard or not, is E0384. Making the scrutinee mutable does not cure E0510, and making a binding mutable does not cure E0594; in both cases the cure starts by moving the assignment past the guard, into the arm — and for a pattern binding, the binding must also be declared mut in the pattern, or the arm-body assignment fails with E0384 instead.

The exact rule: while a guard runs, the matched value is held by shared reference

The official page for E0510 states the rule in one sentence: the matched value was assigned in a match guard. Its explanation is the exhaustiveness argument. When matching on a variable, it cannot be mutated in the match guards, as this could cause the match to be non-exhaustive — executing the assignment would modify the value being matched and require going back in time to an arm already passed. Its stated fix is the first fix above: to fix it, change the value in the match arm.

The Reference's page on match expressions gives the mechanism underneath. Match arms can accept match guards, and when the pattern matches successfully the guard is executed; if the guard evaluates to false, the next pattern is tested. Before evaluating the guard, a shared reference is taken to the part of the scrutinee the variable matches on, and while evaluating the guard that shared reference is used when accessing the variable — and, in the Reference's words, by holding a shared reference while evaluating the guard, mutation inside guards is also prevented. The same page notes that variables bound within the pattern are scoped to the match guard and the arm's expression, which is the scoping behind the E0594 case: the binding exists inside the guard, but exists there as an immutable borrow of the scrutinee, not as an owned value the guard may overwrite.

The Cell case above is the boundary of that mechanism, and the same Reference page marks it: it shows a guard calling a Cell set method and notes that multiple matches using the | operator can cause the pattern guard and the side effects it has to execute multiple times. Interior-mutability effects are not assignments to the matched place, so the shared-reference rule does not stop them — which is exactly why they are dangerous in a guard. The guard is a test, possibly a repeated one, and its effects through a Cell or a RefCell survive a false result.

The fixes, ranked

  • First, move the assignment from the guard into the body of the arm it guards. This is the compiler documentation's own repair, it keeps the match structure intact, and it is what most E0510 code actually meant: the assignment was an action, not a condition.
  • Second, when the guard is a genuine condition with an assignment as its consequence, compute the condition before the match and let the guard only read the result. The assignment still lands in the arm; the guard becomes a plain boolean read.
  • Third, when the match tests a value for presence and little else, replace it with an if let. There is no guard context in an if let body, so the assignment is ordinary code — but keep real multi-arm matches as matches.
  • Fourth, when the scrutinee is a field or another place expression, apply the same moves to that place. The ban follows the matched place, so the arm body is where that place gets assigned.
  • Do not reach for interior mutability to mutate from inside a guard. A Cell set in a guard compiles, but it runs even when the guard returns false and its arm is skipped, and it can run more than once when patterns are joined with |.

Which fix for which cause

Cause Message Fix
Guard assigns the matched variable E0510, cannot assign state in match guard Move the assignment into the arm body
Guard both tests outside state and assigns E0510, same header naming the scrutinee Compute the condition before the match; guard reads a flag
Two-case match with a clearing guard E0510 on the Some arm's guard Replace the match with an if let
Scrutinee is a struct field E0510, cannot assign config.port in match guard Assign the field in the arm body
Guard assigns a pattern binding E0594, immutable for the pattern guard Use the binding read-only in the guard; assign in the arm, with the binding declared mut
Guard assigns an unrelated immutable variable E0384, cannot assign twice to immutable variable Declare the variable mut, as anywhere else
Guard mutates through a Cell No error; side effect survives a false guard Not a fix — move the mutation into an arm

Checklist

  • Find the assignment whose target is the scrutinee. The error underlines the scrutinee itself with value is immutable in match guard; that underline, not the variable's declaration, tells you which place is protected.
  • Do not add mut and recompile. The scrutinee in the first example is already mut; E0510 is about where the assignment sits, not about the declaration.
  • Move actions out of guards and conditions into them. A guard should finish by producing a boolean; anything it was changing belongs in an arm body or before the match.
  • Check pattern bindings separately. If the span names a binding rather than the scrutinee, the code is E0594, and the binding stays read-only until the arm body in exactly the same way — and an arm-body assignment to it needs the binding declared mut in the pattern.
  • Treat a guard that compiles while mutating a Cell or RefCell as a bug, not a workaround. Run the failing-guard case and confirm the value afterward; the mutation survives the guard returning false.
  • After the fix, confirm the value ends in the state the guarded code intended. The fixed programs here print the matched value from the arm and the variable's final state after the match, and both lines are part of the expected output.

Sources

  • Rust Compiler Error Index, E0510 — for the matched value being assigned in a match guard, for mutation in a guard risking a non-exhaustive match by changing the value being matched, and for the fix of changing the value in the match arm.
  • The Rust Reference, Match expressions — for guards executing after a pattern matches with the next pattern tested when a guard is false, for the shared reference taken to the scrutinee before a guard runs and mutation being prevented while it is held, for pattern bindings being scoped to the guard and the arm, and for guard side effects through a Cell being able to execute multiple times.

Keep Exploring