0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rustにおける変数の不変性と可変性

Last updated at Posted at 2021-03-18

Rustにおける変数の不変性

  • Rustでは、変数は不変を推奨しています。
  • 変数が不変とは、値が一旦名前と結びつけられたら、その値を変えることができないことを指します。

fn main() {
    let x = 5;
    println!("The value of x is: {}", x);
    x = 6;
    println!("The value of x is: {}", x);
}

実行結果

❯ cargo run                
   Compiling variables v0.1.0 (/Users/yoshitaka.koitabashi/Desktop/variables)
error[E0384]: cannot assign twice to immutable variable `x`
 --> src/main.rs:4:5
  |
2 |     let x = 5;
  |         -
  |         |
  |         first assignment to `x`
  |         help: make this binding mutable: `mut x`
3 |     println!("The value of x is: {}", x);
4 |     x = 6;
  |     ^^^^^ cannot assign twice to immutable variable

error: aborting due to previous error

For more information about this error, try `rustc --explain E0384`.
error: could not compile `variables`

To learn more, run the command again with --verbose.
  • 実行結果から分かるように、コンパイルエラーで落ちています。
  • エラーの原因は、不変変数xに2回代入(変数に別の値を代入)できない為です。

=> Rustでは、値が不変だと宣言したら、変わらないことをコンパイラが担保します。

Rustにおける変数の可変性

  • Rustにおいて、変数を不変としてしか扱えない訳ではない。(標準として、不変なだけ)
  • 変数名の前にmutを付けることで、可変にできます

fn main() {
    let mut x = 5;
    println!("The value of x is: {}", x);
    x = 6;
    println!("The value of x is: {}", x);
}

実行結果

❯ cargo run
   Compiling variables v0.1.0 (/Users/yoshitaka.koitabashi/Desktop/variables)
    Finished dev [unoptimized + debuginfo] target(s) in 0.94s
     Running `target/debug/variables`
The value of x is: 5
The value of x is: 6

Rustにおける定数

変数の値を変更できないようにする概念として定数があります。
ただ、変数と定数での違いがありそれが下記です。

  • mutは使えない。(常に不変である為)
  • letの代わりに、constで宣言し、値の型は必ず注釈しないといけない
  • どんなスコープでも定義できる。(グローバルスコープも含めて)
  • 定数式にしか設定できない(関数呼び出し結果や、実行時に評価される値にはセットできない)
  • プログラムが走る期間、定義されたスコープ内でずっと有効

const MAX_POINTS: u32 = 100_000;

参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?