Zenn
🎃

[rust] 通常は不変の変数を可変にする方法

2025/01/02に公開

Rustでは通常、変数は全て不変である。

以下のコードの実行結果を確認してみてください。


fn main() {
    let x = 5;
   println!("x = {:?}", x);
   
   x = 10;
   println!("x = {:?}", x);
}

出力結果は以下のようになります。

   Compiling playground v0.0.1 (/playground)
error[E0384]: cannot assign twice to immutable variable `x`
  --> src/main.rs:11:4
   |
8  |     let x = 5;
   |         - first assignment to `x`
...
11 |    x = 10;
   |    ^^^^^^ cannot assign twice to immutable variable
   |
help: consider making this binding mutable
   |
8  |     let mut x = 5;
   |         +++

For more information about this error, try `rustc --explain E0384`.
error: could not compile `playground` (bin "playground") due to 1 previous error

つまり、普遍の変数には値を2回割り当ててはいけないよと言われています。

変数を可変にする方法もある

変数の前にmutという文字列をつける。
するとコードは以下のようになります。

fn main() {
    let mut x = 5;
   println!("x = {:?}", x);
   
   x = 10;
   println!("x = {:?}", x);
}

出力結果は以下のようになります。

x = 5
x = 10

Discussion

ログインするとコメントできます