If let

Using if let instead of match

I am using the Zed editor. Built with Rust to be fast. With a vision to change how programmers collaborate.

Code

pub fn execute() {
    println!("--- let vs match ---");
    let optional = Some(10);

    // The if let way
    if let Some(i) = optional {
        println!("Matches and it is {i}");
    } else {
        println!("Doesn't match!");
    }

    // The match way
    match optional {
        Some(i) => println!("Matches and it is {i}"),
        _ => println!("Doesn't match!"),
    }

    println!();
}

Check it on GitHub.

Thoughts

The two statements are equivalent. Which one is better looking can be a personal preference. I like both to be honest. I guess it depends on the number of different branches and the code involved for each branch.

Let me explain what is happening here. In Rust there's a way to express that a value is either Some(<something>) or None. That's what we are doing with let optional = Some(10). We are saying, let variable optional be some integer.

Then, with the "if let" satement, we are saying, if optional is some integer number instead of none, put that number in i and go to the true branch. If not, go to the other branch.

Likewise, the match statement checks optional and matches the branches below.

The syntax is different but the idea is the same.

A small difference

Actually there's a small difference. With the match statement, I have to include the None (or _) pattern case. With the if let statement, though, I don't if I don't care about None. I could have written it like so:

if let Some(i) = optional {
    println!("Matches and it is {i}");
}

And the complier would be fine. Wouldn't complain.

Last updated