Rust基础08-模式匹配

模式匹配

  • 控制流运算符——match:

    其允许一个值与一系列模式进行匹配,并执行匹配的模式对应的代码

    这些模式可以是字面值、变量名、通配符...

    绑定值的模式:

    匹配的分支可以绑定到被匹配对象的部分值

    因此,可以从 enum 变体中提取值

    //绑定值
    #[derive(Debug)]
    enum UsState {
        Alabama,
        Alaska,
    }
    
    enum Coin {
        Penny,
        Nickel,
        Dime,
        Quarter(UsState),
    }
    
    fn value_in_cents(coin: Coin) -> u8 {
        match coin {
            Coin::Penny => {
                println!("Penny");
                1
            }
            Coin::Nickel => 5,
            Coin::Dime => 10,
            Coin::Quarter(state) => {
                println!("State quarter from {:?}!", state);
                25
            }
        }
    }
    
    fn main() {
        let c = Coin::Quarter(UsState::Alaska);
        println!("{}", value_in_cents(c));
    }
    

    匹配 Option

    //匹配Option<T>
    fn main() {
        let five = Some(5);
        let six = plus_one(five);
        let none = plus_one(None);
    }
    
    fn plus_one(x: Option<i32>) -> Option<i32> {
        match x {
            None => None,
            Some(i) => Some(i + 1),
        }
    }
    

    match 匹配必须穷举所有的可能:

    _通配符:替代其余未列出的值

    fn main() {
        let v = 0u8;
        match v {
            1 => println!("one"),
            3 => println!("three"),
            5 => println!("five"),
            7 => println!("seven"),
            _ => (),
        }
    }
    
  • if let:

    处理时,只关心一种匹配,而忽略其它匹配的情况,其放弃了穷举的可能:

    fn main() {
        //match
        let v = Some(0u8);
        match v {
            Some(3) => println!("three"),
            _ => (),
        }
    	//if let
        if let Some(3) = v {
            println!("three");
        } else {
            println!("others");
        }
    }
    
    

    可以将 if let 看作是 match 的语法糖。

posted on 2022-04-07 22:10  Baby091  阅读(102)  评论(0编辑  收藏  举报

导航