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 assignReal 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.
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
Up next
Often hit nextE0004: non-exhaustive patternsA related error from the same family.Read it next →Did this answer your question?