Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 626
Tommy Avatar asked Dec 31 '22 17:12

Tommy


1 Answers

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...".

like image 51
Peter Hall Avatar answered Jan 10 '23 22:01

Peter Hall