[Pre-RFC] Alternative syntax for pattern-matching based branching

I had a little experience with mentoring/teaching/helping people get into Rust. A very common problem for newcomers that I encountered was if let, I just went ahead and counted this: out of 11 people 7 had issues with if let.

For example they would get confused about if let Some(x) = option trying to write it like this: if Some(let x) == option or other ways. Basically it was confusing to them why there was a let involved at that position.

This problem isn't part of the motivation of this Pre-RFC:

The current if let and while let syntax makes it easy for programmers to confuse let statements as expressions (with a following :wink: that return bool values.`

Which isn't a problem I personally have encountered so far, but as Centril proposed I can see how this could actually be a very useful thing if it would work in Rust.

I'm not sure what the general stance in Rust is for changing syntax only for the sake of a better/more intuitive/easier one, but in my personal opinion if syntax can be improved than I think it should and editions make it "easy" to deprecate old syntaxes.

Personally I do think that the syntax proposed by the Pre-RFC is definitly more intuitive than if let and therefore better, so I'm in favor of that. But this could also be combined with Centrils proposition to make it a bool expression.

So match <expr> : <pattern> could be a bool expression too.

But if Rust is generally not in the business of changing syntax just for the sake of a better/more intuitive/easier one I can see how leaning into the user's confusion instead of changing the syntax is the path of least resistance.

2 Likes

Yeah, let is not a good syntax for pattern matching expressions.
It has multiple issues starting from the unnatural operand order, continuing syntactic ambiguities.
Another alternative that got some people's love, at least in terms of likes, is EXPR is PAT.

1 Like

I like the idea, but at the same time I think the challenge here is that we're doing both destructuring (where PAT before EXPR is the more usual syntax IMO) and matching (where EXPR before PAT is more common). So while for the simple cases EXPR is PAT definitely makes more sense, for more complex cases if let might feel more natural.

The use of let makes some amount of sense because it's also used for unconditional destructuring; in a sense, I guess even the simplest variable definitions can be considered patterns. In a sense, its use could be orthogonal to the order, though, if we go with something like if Some(bar) <= foo. I suppose that proposal also wouldn't work since it will confuse "less than or equal to" with the matching syntax.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.