为什么在Rust中我们使用if-let而不是if?是否还有其他原因?

23

我不明白为什么我们要使用if let而不是普通的if。 在Rust书的第6.3章,示例代码如下:

let some_u8_value = Some(0u8);
if let Some(3) = some_u8_value {
    println!("three");
}

上面的代码与以下代码相同:

let some_u8_value = Some(0u8);
if Some(3) == some_u8_value {
    println!("three");
}

我们使用 if let 的其他原因是什么,或者它具体用于什么?

2个回答

11

另一个原因是如果您希望使用模式绑定。例如,考虑一个枚举:

enum Choices {
  A,
  B,
  C(i32),
}

如果您希望对 ChoicesC 变体实现特定逻辑,您可以使用 if-let 表达式:

let choices: Choices = ...;

if let Choices::C(value) = choices {
    println!("{}", value * 2);
}

3
一个 if let 表达式在语义上类似于 if 表达式,但是它期望的不是条件表达式,而是关键字 let,后跟模式、等号和一个待检查的表达式。如果待检查表达式的值与模式匹配,则相应的代码块将被执行。否则,如果存在 else 块,则流程继续到下一个 else 块。与 if 表达式类似,if let 表达式的值由评估的代码块决定。 来源 if let 可以用来匹配任何枚举值:
enum Foo {
    Bar,
    Baz,
    Qux(u32)
}

fn main() {
    // Create example variables
    let a = Foo::Bar;
    let b = Foo::Baz;
    let c = Foo::Qux(100);

    // Variable a matches Foo::Bar
    if let Foo::Bar = a {
        println!("a is foobar");
    }

    // Variable b does not match Foo::Bar
    // So this will print nothing
    if let Foo::Bar = b {
        println!("b is foobar");
    }

    // Variable c matches Foo::Qux which has a value
    // Similar to Some() in the previous example
    if let Foo::Qux(value) = c {
        println!("c is {}", value);
    }

    // Binding also works with `if let`
    if let Foo::Qux(value @ 100) = c {
        println!("c is one hundred");
    }
}

非常详细。谢谢 - Russo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接