Tommy
Tommy

Reputation: 809

How to "read" if let expressions?

In Rust, you can use if let instead of match when it comes to unwrapping and directly using just a simple value.

So instead of

match opt_val {
    Some(x) => {
        do_something_with(x);
    }
    _ => {}
}

you can do

if let Some(x) = opt_val {
    do_something_with(x);
}

How should I read or process this code mentally? For match, this is straightforward: "If opt_val is matched by Some(x) then do... with x".

For if let I always have the impression that it is the wrong way round: "If Some(x) matches(?) opt_val, then do....". Note that there is no let in this sentence.

It is no big deal, but I continue to stumble over this.


I really like "if this let binding succeeds then..." from the accepted answer, as I think it sets the right focus. Concentrating too much on the pattern matching got me into this "problem" in the first place. For reference, (ir)refutability and let is discussed here in the Rust book.

Upvotes: 11

Views: 1279

Answers (1)

Peter Hall
Peter Hall

Reputation: 58725

You shouldn't expect the keywords in the syntax of any programming language to map directly to words in English, or any other natural language.

let expressions in Rust always accept a pattern, which lets you do things like:

let foo = (1, (2, 3));
let (a, (b, _)) = foo;

However, this only works when the pattern is irrefutable, that is it will always match.

if let extends this to accommodate types that may not always match.

How you are reading it is just fine: "if the pattern matches then...", or "if this let binding succeeds then...".

Upvotes: 19

Related Questions