本文へスキップ
BecomeCoder

Rustのエラー · エラー7

E0384: cannot assign twice to immutable variable ― 不変変数への再代入

Rust の変数は既定で**不変(immutable)**です。mut を付けずに宣言した変数へ2回目の代入をすると出ます。

出るコード

fn main() {
    let x = 1;
    x = 2;   // x は mut ではない
    println!("{}", x);
}

エラーメッセージ

error[E0384]: cannot assign twice to immutable variable `x`

直し方

書き換える変数には let mut x = 1; のように mut を付けます。