我们在 Rust 中使用 if-let 而不是 if 的任何其他原因?

Any other reason why we use if-let rather than if in Rust?

我不明白为什么我们使用 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 的任何其他原因或者它的具体用途是什么?

An if let expression is semantically similar to an if expression but in place of a condition expression it expects the keyword let followed by a pattern, an = and a scrutinee expression. If the value of the scrutinee matches the pattern, the corresponding block will execute. Otherwise, flow proceeds to the following else block if it exists. Like if expressions, if let expressions have a value determined by the block that is evaluated.

Source

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");
    }
}

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

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

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

let choices: Choices = ...;

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