Rust match 和 if let

CargoRun發表於2020-11-02

The match Control Flow Operator
控制流運算子match

Patterns That Bind to Values
繫結值的模式
[ugly programs,isn’t it?]

fn main() {
    let x = Week:: Weekend(Home:: Music);
    let r = match_week(x);
    println!("Hello, {:?}!", r);
}
#[derive(Debug)]
enum Work {
    Chinese,
    Computer,
    English,
    Math,
    Nature,
}
#[derive(Debug)]
enum Home {
    Music,
    Sleep,
    Swimming,
}
#[derive(Debug)]
enum Week {
    Workday(Work),
    Weekend(Home),
}
fn match_week(x: Week) -> Week {
    match x {
        Week::Workday(Work::Chinese) => {
            println!("好好學習,天天向上.");
            Week::Workday(Work::Chinese)
        },
        Week::Workday(Work::Computer) => {
            println!("0b1111_1110_1100_1000 = ?");
            Week::Workday(Work::Computer)
        },
        Week::Workday(Work::English) => {
            println!("good good study, day day up.");
            Week::Workday(Work::English)
        },
        Week::Workday(Work::Math) => {
            println!("1 + 1 = ?");
            Week::Workday(Work::Math)
        },
        Week::Workday(Work::Nature) => {
            println!("Protect the Environment, Everyone Duty.");
            Week::Workday(Work::Nature)
        },
        Week::Weekend(Home::Music) => {
            println!("The Voice of China");
            Week::Weekend(Home::Music)
        },
        Week::Weekend(Home::Swimming) => {
            println!("One World One Dream");
            Week::Weekend(Home::Swimming)
        },
        _ => Week::Weekend(Home::Sleep),
    }
}

Matching with Option
匹配Option

fn main() {
    let five = Some(5);
    let six = plus_one(five);
    let none = plus_one(None);
    println!("five:{:?}", five);
    println!("six:{:?}", six);
    println!("none:{:?}", none);
}
fn plus_one(x: Option<i32>) -> Option<i32> {
    match x {
        None => None,
        Some(i) => Some(i + 1),
    }
}

Matches Are Exhaustive
匹配必須窮舉所有可能
The _ Placehoder
萬用字元_

fn main() {
    let some_u8_value = 0u8;
    match some_u8_value {
        1 => println!("one"),
        3 => println!("three"),
        5 => println!("five"),
        7 => println!("seven"),
        _ => println!("Hello, world!"),
    }
}

Concise Control Flow with if let
簡單控制流if let

fn main() {
    let x: u32 = 64;
    let r = if_let(x);
    println!("The value of r is {}.", r);
}
fn if_let(x: u32) -> u32 {
    if let 32 = x {
        println!("The number is 32.");
        32
    } else {
        println!("The number is not 32.");
        x
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結
艱難困苦,玉汝於成

相關文章