解决 Rust 编译报错 cannot mutate immutable variable 的排查指南
排查与解决 Rust 编译器核心可变性检查提示 cannot mutate immutable variable E0384 的完整方案。
问题现象
在编译 Rust 代码时,cargo build 提示 E0384 不可变变量修改错误:
error[E0384]: cannot assign twice to immutable variable `counter`
--> src/main.rs:12:5
|
10 | let counter = 0;
| -------
| |
| first assignment to `counter`
| help: consider making this binding mutable: `mut counter`
11 | // ...
12 | counter += 1;
| ^^^^^^^^^^^^ cannot assign twice to immutable variable
触发根因
- Rust 语言核心的默认不可变(Immutable by default)设计:在 Rust 中,使用
let x = 5;声明的变量默认是严格只读的,禁止二次赋值。 - 代码后续执行了重新赋值(
counter = 10)或就地修改(counter += 1),违反了不可变性约束。 - 试图对未标记为
mut的结构体实例执行成员字段修改。
解决步骤与操作命令
步骤一:在变量声明时添加 mut 关键字显式标记为可变(推荐)
若该变量在业务逻辑中需要发生变化,显式使用 let mut:
// 添加 mut 关键字允许修改
let mut counter = 0;
counter += 1;
println!("Current count: {}", counter);
步骤二:利用 Rust 的变量遮蔽(Variable Shadowing)机制
若只是需要对数据进行类型转换或多步计算,使用 let 进行重影遮蔽(无需 mut):
let spaces = " ";
// 使用 shadowing 转换类型与值
let spaces = spaces.len();
println!("Spaces count: {}", spaces);
步骤三:修改结构体实例声明为 mut
若需要修改结构体的内部字段,实例本身必须声明为可变:
struct Point {
x: i32,
y: i32,
}
// 必须声明为 let mut
let mut pt = Point { x: 0, y: 0 };
pt.x = 10;
验证确认
在终端执行代码检查:
cargo check
代码顺利通过可变性检查与借用分析,未再产生任何 E0384 cannot mutate immutable variable 报错。


