E0502
rust
type_error
ai_generated
partial
error[E0502]: cannot borrow `x` as immutable because it is also borrowed as mutable in match guard
ID: rust/e0502-cannot-borrow-as-immutable-in-match-guard
78%Fix Rate
83%Confidence
1Evidence
2023-04-05First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| rustc 1.60.0 | active | — | — | — |
| rustc 1.67.0 | active | — | — | — |
| rustc 1.73.0 | active | — | — | — |
Root Cause
Match guards create a mutable borrow that conflicts with an immutable borrow in the same scope, violating Rust's borrowing rules.
generic中文
match 守卫创建了一个可变借用,与同一作用域中的不可变借用冲突,违反了 Rust 的借用规则。
Official Documentation
https://doc.rust-lang.org/error_codes/E0502.htmlWorkarounds
-
80% success Restructure the match to avoid mutable borrow in guard: move the mutable operation inside the arm body using `if let` or separate match.
Restructure the match to avoid mutable borrow in guard: move the mutable operation inside the arm body using `if let` or separate match.
-
75% success Use `Cell` or `RefCell` for interior mutability: `let x = Cell::new(5); match x.get() { ... }`
Use `Cell` or `RefCell` for interior mutability: `let x = Cell::new(5); match x.get() { ... }` -
85% success Extract the guard logic into a separate function that takes immutable references.
Extract the guard logic into a separate function that takes immutable references.
中文步骤
重构 match 以避免在守卫中进行可变借用:将可变操作移到 arm 主体内,使用 `if let` 或单独的 match。
使用 `Cell` 或 `RefCell` 实现内部可变性:`let x = Cell::new(5); match x.get() { ... }`将守卫逻辑提取到接受不可变引用的单独函数中。
Dead Ends
Common approaches that don't work:
-
85% fail
The mutable borrow in the guard still conflicts because the immutable reference x_ref is still alive in the match scope.
-
70% fail
If x is a large struct or not Clone, this may not be feasible. Also, cloning doesn't solve the borrowing conflict if the original is still mutably borrowed.
-
60% fail
The mutable borrow may be necessary for the match arm's logic. Removing it changes program semantics.