Sibainu Relax Room

柴犬と過ごす

RUST match の使い方

はだか祭の準備も進んでいるようだなと思う柴犬です。

概要

ここ数日、RUST を勉強しています。

この中で、改めて match 関数の重要性・利便性を認識しましたので、RUSTの次のホームページ(Rust by Example)を読み直しました。

Rust by Example
8. Flow of Control
8.5. match
8.5.1. Destructuring
https://doc.rust-lang.org/rust-by-example/flow_control/match/destructuring.html

読む過程で、その中にある例を全部実行してみました。

match 関数の例が手際よくまとめているので、今後、役立つようにと思い投稿することにしました。

tuple

実行したコード

fn main() {
    // 例1
    let triple = (0, -2, 3);
    // 例2 let triple = (1, -2, 3);
    // 例3 let triple = (4, -2, 2);
    // 例4 let triple = (3, -2, 4);
    // 例5 let triple = (5, -2, 3);

    println!("Tell me about {:?}", triple);

    match triple {

        (0, y, z) => println!("First is `0`, `y` is {:?}, and `z` is {:?}", y, z),

        (1, ..)  => println!("First is `1` and the rest doesn't matter"),

        (.., 2)  => println!("last is `2` and the rest doesn't matter"),

        (3, .., 4)  => println!("First is `3`, last is `4`, and the rest doesn't matter"),

        _      => println!("It doesn't matter what they are"),
    }
}

実行の結果を例毎に示しています。

arrays/slices

実行したコード

fn main() {

    // 例1
    let array = [0, -2, 2, 8, 6];
    // 例2 let array = [1, -2, 2, 8, 6];
    // 例3 let array = [-1, -2, 2, 8, 6];
    // 例4 let array = [3, -2, 2, 8, 6];
    // 例5 let array = [5, -2, 2, 8, 6];

    println!("Tell me about {:?}", array);

    match array {
        [0, second, third, ..] =>
            println!("array[0] = 0, array[1] = {}, array[2] = {}", second, third),

        [1, _, third, ..] => println!(
            "array[0] = 1, array[2] = {} and array[1] was ignored",
            third
        ),


        [-1, second, ..] => println!(
            "array[0] = -1, array[1] = {} and all the other ones were ignored",
            second
        ),

        [3, second, tail @ ..] => println!(
            "array[0] = 3, array[1] = {} and the other elements were {:?}",
            second, tail
        ),

        [first, middle @ .., last] => println!(
            "array[0] = {}, middle = {:?}, array[2] = {}",
            first, middle, last
        ),
    }
}

実行の結果を例毎に示しています。

enum

実行したコード

#[derive(Debug)]
#[allow(dead_code)]
enum Color {
    Red,
    Blue,
    Green,
    RGB(u32, u32, u32),
    HSV(u32, u32, u32),
    HSL(u32, u32, u32),
    CMY(u32, u32, u32),
    CMYK(u32, u32, u32, u32),
}

fn main() {

    //例1 
    let color = Color::Red;
    //例2 let color = Color::Blue;
    //例3 let color = Color::Green;
    //例4 let color = Color::RGB(122, 17, 40);
    //例5 let color = Color::HSV(20, 30, 40);
    //例6 let color = Color::HSL(50, 60, 70);
    //例7 let color = Color::CMY(180, 190, 200);
    //例8 let color = Color::CMYK(210, 220, 230, 240);

    println!("What color is it? {:?}", color);

    match color {
        Color::Red   => println!("The color is Red!"),
        Color::Blue  => println!("The color is Blue!"),
        Color::Green => println!("The color is Green!"),
        Color::RGB(r, g, b) =>
            println!("Red: {}, green: {}, and blue: {}!", r, g, b),
        Color::HSV(h, s, v) =>
            println!("Hue: {}, saturation: {}, value: {}!", h, s, v),
        Color::HSL(h, s, l) =>
            println!("Hue: {}, saturation: {}, lightness: {}!", h, s, l),
        Color::CMY(c, m, y) =>
            println!("Cyan: {}, magenta: {}, yellow: {}!", c, m, y),
        Color::CMYK(c, m, y, k) =>
            println!("Cyan: {}, magenta: {}, yellow: {}, key (black): {}!",
                c, m, y, k),
    }
}

実行の結果を例毎に示しています。

pointers/ref

実行したコード

fn main() {

    let reference = &4;

    match reference {
        &val => println!("Got a value via destructuring: {:?}", val),
    }

    match *reference {
        val => println!("Got a value via dereferencing: {:?}", val),
    }

    let value = 5;
    let mut mut_value = 6;

    match value {
        ref r => println!("Got a reference to a value: {:?}", r),
    }

    match mut_value {
        ref mut m => {
            *m += 10;
            println!("We added 10. `mut_value`: {:?}", m);
        },
    }
}

実行の結果を示しています。

structs

実行したコード

#[derive(Debug)]    
struct Foo {
    // タプル
    x: (u32, u32),
    // 符号無し整数
    y: u32,
}

fn main() {

    //例1 
    let foo = Foo { x: (1, 2), y: 3 };
    //例2 let foo = Foo { x: (2, 2), y: 2 };
    //例3 let foo = Foo { x: (3, 2), y: 3 };

    println!("{:?}", foo);

    match foo {
        Foo { x: (1, b), y } => println!("First of x is 1, b = {},  y = {} ", b, y),

        Foo { y: 2, x: i } => println!("y is 2, i = {:?}", i),

        Foo { y, .. } => println!("y = {}, we don't care about x", y),
    }
}

実行の結果を例毎に示しています。