【问题标题】:Is there a difference between "if let" and "if"?“如果让”和“如果”之间有区别吗?
【发布时间】:2020-04-19 05:36:08
【问题描述】:

代码:

let x = Some(3);
if x == Some(3) {
    println!("if case");
}
if let Some(3) = x {
    println!("if let case");
}

结果:

if case
if let case

为什么 rust 程序员使用“if let”?

【问题讨论】:

    标签: rust pattern-matching


    【解决方案1】:

    使用if let,您可以使用模式匹配将x 分解为多个部分:

    let x = Some(3);
    if let Some(v) = x {
        println!("{}", v); // prints 3
    }
    

    if 相同的是不雅:

    let x = Some(3);
    if x.is_some() {
        println!("{}", x.unwrap()); // not recommended
    }
    

    (playground)

    【讨论】:

      猜你喜欢
      • 2014-08-07
      • 1970-01-01
      • 1970-01-01
      • 2018-11-29
      • 1970-01-01
      • 1970-01-01
      • 2012-02-16
      • 2016-02-14
      • 1970-01-01
      相关资源
      最近更新 更多