1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Rustは式ベースのプログラミング言語なので、式と文について正しく理解しようと思い、これを書いた。

式と文

"式" とは"値を返すもの"であり、
"文" とは"宣言"である。

まずは文の具体例を示そう。

let a = 10;
1+2;
fn foo() {}

1番上は「10という数値をaに代入する(変数束縛する)」という宣言
2番目は「1に2を加える」という宣言
3番目は「foo()という関数を定義する」という宣言

ちなみに以下のような構文はエラーになる。
fn foo() {}というのはあくまで"宣言"で値ではないため、それをfに代入(束縛)することはできない。

let f = fn foo() {}; //エラー

値の具体例を示そう。

{10}
{1+2}

これだけだと自明すぎてわからないので、もう少し実用的な例を示す。

fn main() {
    let x = 10;

    let result = match x {
        n if n > 0 => "positive",
        0 => "zero",
        _ => "negative",
    };
    println!("result = {}", result);
}

これは、Rustを扱う上でもっとも使用頻度が高いといっても過言ではないmatch式だ。
上記の処理内容を日本語で書くと

  1. xに10を代入する
  2. xが0より大きいならpositive、0ならzero、それ以外ならnegativeをresultに代入する
  3. resultが保有する値をプリントする

となる

match x {
        n if n > 0 => "positive",
        0 => "zero",
        _ => "negative",
    }

matchというのはRustが標準搭載している関数で、"値を返す"。
つまりこの部分は丸っと"値"なので、resultに代入することが可能。
他にも

fn add(a: i32, b: i32) -> i32 {
    a + b
}

これは関数宣言の例だが、下記の部分

{
    a + b
}

これはまさに"値"だ。つまりaddという関数は"値を返す"と"宣言"している。
よって、こんな使い方になる。

fn main(){
    let result = add(10,2);
    println!("{}",result);
}

fn add(a: i32, b: i32) -> i32 {
    a + b
}

add(10,2)が"丸っと値"だと理解すれば、きちんと構文を理解したことになる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?