gpt4 book ai didi

rust - Rust 中 if 和 if-let 的主要区别

转载 作者:行者123 更新时间:2023-12-03 11:23:52 30 4
gpt4 key购买 nike

我不明白我们使用 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");
}
}

关于rust - Rust 中 if 和 if-let 的主要区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59692380/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com