logoalt Hacker News

bernds74yesterday at 3:10 PM1 replyview on HN

"if let" just breaks my brain, it feels backwards to me and takes me a minute each time to work out what's going on. In 40 years of programming I've never seen a syntactic construct that I found less intuitive. And it would probably be easily fixable, if it was more along the lines of "if x matches Some(let z)".


Replies

ai_yesterday at 9:43 PM

if let makes a lot more sense when you learn that a normal let expression also takes a pattern[1].

  let Coordinates(x, y) = get_coords();
But this is intended for "exhaustive patterns". If you can't express an exhaustive pattern, like with an Option, then you can use let ... else

  let Some((x, y)) = get_coords() else { return };
if let is just an extension of this "let pattern" system.

Once you internalize how patterns work (and they really work everywhere) it all starts to really make sense and feels a lot cleaner.

[1]: https://doc.rust-lang.org/reference/patterns.html