earlgray283
earlgray283

Reputation: 145

Is there a difference between "if let" and "if"?

Code:

let x = Some(3);
if x == Some(3) {
    println!("if case");
}
if let Some(3) = x {
    println!("if let case");
}

Result:

if case
if let case

Why do rust programmers use "if let" ?

Upvotes: 5

Views: 193

Answers (1)

L. F.
L. F.

Reputation: 20579

With if let, you can use pattern matching to decompose x into parts:

let x = Some(3);
if let Some(v) = x {
    println!("{}", v); // prints 3
}

The same thing with if is inelegant:

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

(playground)

Upvotes: 8

Related Questions