I have a hard time understanding the "if let" syntax

IMO the problem is that people coming to Rust generally are experienced in simple assignment, so don't realize that Rust's left-hand sides are patterns rather than single variables or tuples of variables. Maybe teaching materials should emphasize the pattern aspect more, perhaps by emphasizing the duality aspect.

3 Likes

I've been using Rust for awhile and I hadn't fully internalized that fact even though I've made use of it.

I had thought of if let as a funny looking if statement. So the syntax didn't totally make sense to me. Looking at it as an extension of the let statement seems obvious in retrospect but it hadn't clicked for me until this thread.

FWIW, function argument names are also patterns, just like irrefutable let. I think this is not well known, but maybe folks who know also avoid it just to keep sanity in formatting. :crazy_face:

3 Likes

You are right! I read that somewhere and then proceeded to immediately forget it!
But we can totally do this:

struct MyStruct{ foo:i32}

fn a_function(MyStruct { foo: bar }: MyStruct) -> i32 {
    bar
}

:innocent:

3 Likes

I have a feeling very few people know/remember this :exploding_head:

Off-topic: Now pray for anonymous struct

in your case, a == is enough.

if Some(3)==some_value{
  println!("three")
}

if-let syntax is for the propose below:

if let Some(x)=some_value{
  println!("found {}",x)
}

Correct, but it's the example from the book! Concise Control Flow with if let - The Rust Programming Language

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.