I can’t help but suspect it doesn’t offer much and you may as well just use match
statements for whenever you want pattern matching, however many times it might be slightly more verbose than what you could do with if let
.
I feel like I’d easily miss that pattern matching was happening with if let
but will always know with match
what’s happening and have an impression of what’s happening just from the structure of the code.
EDIT: I copied this into a separate post: https://lemmy.ml/post/14593192
yea, great point … I hadn’t considered the consistency with destructuring (which seems silly in hindsight).
For those who aren’t aware, here’s the first section in The Book on patterns in
let
statements.I think, if this is confusing, there are two points of clarification:
let
statements involve patterns. They’re alllet PATTERN = EXPRESSION
. For ordinary variable binding, we’re just providing a basic pattern that is essentially like a wildcard in that it will match the totality of any expression and so be bound to the full/final value of the expression.let (x, y, _) = (1, 2, 3);
or Ephera’s example abovelet Something(different_thing) = something;
which extracts the single field of thestruct
something into the variable
different_thing` (handy!).let
statements must useirrefutable
patterns. That is, patterns that cannot fail to match the expression. For example, against a tuple,(x, y, _)
will always match. Another way of putting it, is thatirrefutable
patterns are about destructuring not testing or conditional logic.if let
statements on the other hand can take bothirrefutable
patterns andrefutable
, but are really intended to be used withrefutable
patterns as they’re intended for conditional logic where the pattern must be able to fail to match the expression/value.refutability
Excellent research! 🙂