マッチ

match

match文はif - else文のショートハンドです。 入力がマッチすると、選択肢の中で最初にマッチした文ブロックを実行し、最後の式を返します。 elseのブロックは、他の選択肢とマッチしなかった場合に実行されます。

num := 1
match num % 2 == 0  {
    true { print('The input number is even.') }
    else { print('The input number is odd.') }
}

matchを使うと、条件に応じたさまざまな値で変数を初期化することもできます。

num := 3
s := match num {
    1 { 'one' }
    2 { 'two' }
    else {
        'many'
    }
}

コード例:

fn even(num int) bool {
    match num % 2 == 0  {
        true { print('The input number is even.') }
        else { print('The input number is odd.') }
    }
}

fn num_to_str(num int) int {
    match num {
        1 { 'one' }
        2 { 'two' }
        else {
            'many'
        }
    }
}

fn main() {
    println(even(14))           // 'The input number is even.'
    println(even(3))            // 'The input number is odd.'
    println(num_to_str(1))      // 'one'
    println(num_to_str(2))      // 'two'
    println(num_to_str(352))    // 'many'
}

enum

.項目名構文を用いることで、選択肢でenumの値(enum`の項目名)とマッチさせることもできます。

Exercises

  1. 1から50までのすべての偶数の配列を作成するVプログラムを書きましょう。

  2. 数値を持つ配列を渡すと、その中の最大値を返すVプログラムを書きましょう。

  3. color(enum)がredかblueかを調べるVプログラムを書きましょう。

Last updated

Was this helpful?