Rust 程式設計視訊教程(進階)——024_1 所有模式的語法 1

linghuyichong發表於2020-02-17

頭條地址:https://www.ixigua.com/i677586170644791348...
B站地址:https://www.bilibili.com/video/av81202308/

github地址:https://github.com/anonymousGiga/learn_rus...

1、匹配字面值
例子:

let x = 1;
match x {
    1 => println!("one"),
    2 => println!("two"),
    3 => println!("three"),
    _ => println!("anything"),
}

2、匹配命名變數
例子:

fn main() {
    let x = Some(5);
    let y = 10;  //1處
    match x {
        Some(50) => println!("Got 50"),
        Some(y) => println!("Matched, y = {:?}", y), //此處的y和上面1處的y不一樣,此處是引入的變數y覆蓋之前的y
        _ => println!("Default case, x = {:?}", x),
    }
    println!("at the end: x = {:?}, y = {:?}", x, y);
}

3、多個模式
例子:

let x = 1;
match x {
    1 | 2 => println!("one or two"),
    3 => println!("three"),
    _ => println!("anything"),
}

說明: |表示或,即匹配1或者2

本作品採用《CC 協議》,轉載必須註明作者和本文連結

令狐一衝

相關文章