“如果让”和“如果”之间有区别吗?

ear*_*283 3 pattern-matching rust

代码:

let x = Some(3);
if x == Some(3) {
    println!("if case");
}
if let Some(3) = x {
    println!("if let case");
}
Run Code Online (Sandbox Code Playgroud)

结果:

if case
if let case
Run Code Online (Sandbox Code Playgroud)

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

L. *_* F. 7

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

let x = Some(3);
if let Some(v) = x {
    println!("{}", v); // prints 3
}
Run Code Online (Sandbox Code Playgroud)

同样的事情if是不雅的:

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

操场