rust控制流运算符 if let

if let

  • 处理只关心一种匹配而忽略其它匹配的情况

  • 例子

    fn main() {
        let v = Some(0u8);
        match v {
            Some(3) => println!("three"),
            _ => println!("others"),
        }
    
        if let Some(3) = v {
            println!("three");
        }
    }
    
  • 更少的代码,更少的缩进,更少的模板代码

  • 放弃了穷举的可能

  • 可以把iflet 看作是 match 的语法糖

  • 搭配 else

    fn main() {
        let v = Some(0u8);
        match v {
            Some(3) => println!("three"),
            _ => println!("others"),
        }
    
        if let Some(3) = v {
            println!("three");
        } else {
            println!("others");
        }
    }
    
posted @ 2022-12-15 22:45  三省吾身~  阅读(89)  评论(0编辑  收藏  举报