Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
676 views
in Technique[技术] by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...