E0384: cannot assign twice to immutable variable の原因と直し方
Rustの変数はデフォルトで不変(immutable)です。letで宣言した変数に後から再代入しようとすると、コンパイル時にE0384エラーになります。
エラーメッセージの読み方
error[E0384]: cannot assign twice to immutable variable `count`
E0384- エラーコード — `rustc --explain E0384` で詳しい説明が見られます
cannot assign twice to immutable variable `count`- 詳細メッセージ — 何が問題だったか
このエラーが出る典型パターン
パターン1
1 fn main() { 2 let count = 5; ^ 3 count = 6; 4 println!("{}", count); 5 }
error[E0384]: cannot assign twice to immutable variable `count`
letで宣言した変数はデフォルトで不変です。値を変更したい場合は、宣言時にmutを付けて明示的にミュータブルにする必要があります。
直し方: (空) を mut にします。
広告
広告スロット(未設定)
パターン2
1 fn main() { 2 let score = 10; ^ 3 score = 20; 4 println!("{}", score); 5 }
error[E0384]: cannot assign twice to immutable variable `score`
mutが無い変数への再代入はコンパイル時に検出されます。実行するまでもなくエラーになります。
直し方: (空) を mut にします。
パターン3
1 fn main() { 2 let total = 100; ^ 3 total = 200; 4 println!("{}", total); 5 }
error[E0384]: cannot assign twice to immutable variable `total`
letの後にmutを付けるかどうかで、その変数が後から書き換え可能かどうかが決まります。
直し方: (空) を mut にします。
パターン4
1 fn main() { 2 let price = 50; ^ 3 price = 75; 4 println!("{}", price); 5 }
error[E0384]: cannot assign twice to immutable variable `price`
constやstaticを付けてもコンパイルは通りません。可変にする唯一の方法はmutです。
直し方: (空) を mut にします。
パターン5
1 fn main() { 2 let age = 20; ^ 3 age = 21; 4 println!("{}", age); 5 }
error[E0384]: cannot assign twice to immutable variable `age`
不変性はRustの基本方針です。書き換える意図がある変数には必ずmutを付けます。
直し方: (空) を mut にします。
よくある誤解
「一度letで宣言した変数なら、後から自由に書き換えられるはず」という思い込みは誤りです。値を変更したい変数には、宣言時にmutを付けて明示的にミュータブルにする必要があります。
まとめ
E0384: cannot assign twice to immutable variableは初級でつまずきやすい項目です。上の5パターンを実際に手で直すと、エラーメッセージのどこを読めばよいかが掴めます。