1
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言語の勉強を初めてみた。その2

Last updated at Posted at 2020-07-16

サンプルコード Variables and Mutabilityを実行してみる

Variables and Mutability

Variables and Mutability

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

x = 6の時に、xはmut指定していないため、ビルドエラーとなる。

VSCodeでもエラーが表示される。

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

これで問題無く動作する。

Differences Between Variables and Constants

定数の定義

const MAX_POINTS: u32 = 100_000;

mutはできない。常に不変。
Rustのコーディング規約では、アンダーバー入りの大文字で書く。

Shadowing

src/main.rs
fn main() {
    let x = 5;

    let x = x + 1;

    let x = x * 2;

    println!("The value of x is: {}", x);
}

mutが無くてもlet指定すれば変数の値を上書きできる。
(上書きというよりかは変数の再定義)

    let spaces = "   ";
    let spaces = spaces.len();

こういう使い方は可能だが、

    let mut spaces = "   ";
    spaces = spaces.len();

こういう使い方はできない。
変数spacesは&str型で定義されているので、
let spaces = spaces.len()のように再定義することで設定可能だが、
spaces = spaces.len()のようにすると変数の型が異なるためエラーとなる。

1
0
1

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
1
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?