Re: [RFC] switch expression
| From: | Larry Garfield | Date: | Wed, 25 Mar 2020 15:46:22 +0000 |
| Subject: | Re: [RFC] switch expression | ||
| References: | 1 2 3 4 5 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-109296@lists.php.net to get a copy of this message | ||
On Wed, Mar 25, 2020, at 10:29 AM, Ilija Tovilo wrote:
> Thanks for your feedback, Larry!
>
> > One possible improvement to either version is allowing an expression on the left side.
> > That is, rather than doing an equality match, do a boolean match.
>
> This is how Rust does it:
>
> ```rust
> let x = match ... {
> Some(y) if y < 5 => ...
> }
> ```
>
> In other words, you can add an additional guard to each case that
> excepts any expression. We don't really benefit a lot from that since
> we don't have pattern matching. I don't think this would add any
> significant benefit over:
>
> ```php
> $x = true switch {
> $x !== null && $x < 5 => ...
> }
> ```
Good point, I'd forgotten about that potential trick. So as long as an expression is allowed
on the left, rather than just a literal, which is then == compared against the provided value, that
should be "good enough" for most use cases.
The implementation should include some tests to make sure that works properly, but I'm happy
with the resulting syntax.
So then the net result is:
$var = switch($val) {
case expr1 => expr2;
}
Where $val gets compared against the result of each expr1, and if true then $var is set to expr2.
Endorse.
--Larry Garfield