-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Bare Switch Capture #20249
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
im not really a fan of this kind of shorthand syntax for things because if you ever need access to the captured variable/error you need to rewrite the surrounding code so the feature ends up becoming a burden. |
I've also considered a shorthand like this before. I think I'm neutral on it. To note in the
Fwiw, this actually isn't the case for
At least in my personal codebase there are at least 5 instances of |
If accepted, I'm not sure the third and fourth ones should be errors - they seem inconsistent with the first two exampples and with the special-case error union switching where the if (expr) |value| switch (value) { BODY }
if (...) else |err| switch (err) { BODY } Or we also change error union switching to also work for the first statement in a block, but I think that would complicate recognition somewhat. |
Uh oh!
There was an error while loading. Please reload this page.
Abstract
Introduce a "bare switch" construct to reduce unnecessary symbol aliasing via captures. This enhancement aims to improve code readability and maintainability by eliminating redundant captures.
Proposal
When an expression:
switch (captured_value)
,captured_value
elsewhere.The capture MUST be omitted and a bare switch must be used.
Examples
The following 4 examples would become compile errors if
BODY
does not use the captured value:Here's the proposed syntax to fix these examples:
Rationale
The bare switch allows payloads to be switched on without introducing a symbol into the scope. This avoids awkward situations where the same value is aliased multiple times.
A common example of this is a
catch
clause like this one:There's around 800 of instances of this pattern in the ziglang github repository. The proposed change would simplify these cases eliminating the need to manage conventions to avoid conflicts with error symbols. This improvement becomes more significant with nested clauses, such as:
Note that there are also dozens of examples with other constructs like
for/if
in the ziglang repository that would also be affected, but this is a minority number of examples in comparison tocatch
.Limitations
This proposal only applies to payloads captured by value. Payloads captured by reference require a symbol to write back to them and therefore wouldn't benefit.
The text was updated successfully, but these errors were encountered: