我不明白为什么我们用if let,而用普通的if.

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或者它的具体用途,还有其他原因吗?

推荐答案

if-let表达式在语义上与if表达式相似,但

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

Rust相关问答推荐

移植带有可变borrow 的C代码-卸载期间错误(nappgui示例)

为什么我的梅森素数代码的指数越大,速度就越快?

使用pyo3::Types::PyIterator的无限内存使用量

在函数内定义impl和在函数外定义impl的区别

不能在一个代码分支中具有不变的自身borrow ,而在另一个代码分支中具有可变的self borrow

如何go 除多余的(0..)在迭代中,当它不被使用时?

如何将单个 struct 实例与插入器一起传递到Rust中的映射

零拷贝按步骤引用一段字节

Rust ndarray:如何从索引中 Select 数组的行

如何在 Rust 中打印 let-else 语句中的错误?

为什么我的trait 对象类型不匹配?

Rust并发读写引起的死锁问题

缺失serde的字段无法设置为默认值

从嵌入式 Rust 中的某个时刻开始经过的时间

我如何将 google_gmail1::Gmail> 传递给线程生成?

带有库+多个二进制文件的Cargo 项目,二进制文件由多个文件组成?

覆盖类型的要求到底是什么?为什么单个元素元组满足它?

Rust:如果我知道只有一个实例,那么将可变borrow 转换为指针并返回(以安抚borrow 判断器)是否安全?

返回 &str 但不是 String 时,borrow 时间比预期长

如何从 Rust 应用程序连接到 Docker 容器中的 SurrealDB?