E0502
rust
type_error
ai_generated
partial
错误[E0502]:无法将 `x` 作为不可变借用,因为它在 match 守卫中也被作为可变借用
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%修复率
83%置信度
1证据数
2023-04-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| rustc 1.60.0 | active | — | — | — |
| rustc 1.67.0 | active | — | — | — |
| rustc 1.73.0 | active | — | — | — |
根因分析
match 守卫创建了一个可变借用,与同一作用域中的不可变借用冲突,违反了 Rust 的借用规则。
English
Match guards create a mutable borrow that conflicts with an immutable borrow in the same scope, violating Rust's borrowing rules.
官方文档
https://doc.rust-lang.org/error_codes/E0502.html解决方案
-
重构 match 以避免在守卫中进行可变借用:将可变操作移到 arm 主体内,使用 `if let` 或单独的 match。
-
使用 `Cell` 或 `RefCell` 实现内部可变性:`let x = Cell::new(5); match x.get() { ... }` -
将守卫逻辑提取到接受不可变引用的单独函数中。
无效尝试
常见但无效的做法:
-
85% 失败
The mutable borrow in the guard still conflicts because the immutable reference x_ref is still alive in the match scope.
-
70% 失败
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% 失败
The mutable borrow may be necessary for the match arm's logic. Removing it changes program semantics.