Increased precedence for 'try' over 'orelse' #5436
Labels
proposal
This issue suggests modifications. If it also has the "accepted" label then it is planned.
Milestone
Given the function signature
The following does not work:
But gives the error
Instead, one must write
This is because the
orelse
operator has higher precedence thantry
.This is related to but distinct from #114 and #2138 as it refers to precedence between two similar operators:
try
andorelse
.Personally, I find
to be much more readable and natural than
The former reads almost like an English sentence and naturally follows the much more common logical flow of "first handle the error case, then handle the null case".
In fact, the paradigm of catching an error before unwrapping an optional (i.e. the
!?
syntax) is much more common than the converse of unwrapping an optional before catching an error (i.e. the?(anyerror!)
syntax): the standard library has about 160 cases of the former while only containing 4 of the latter (from a quickgrep
of the Zig source code). It therefore seems to make sense to increase the precedence oftry
overorelse
since this use case is more common.A counterargument might be that the use of parentheses reduces any ambiguity about which operation comes first (
try
ororelse
); however, there will rarely be ambiguity in the first place since the first pattern is overwhelmingly more common. In the instances that the second pattern is used, one can instead writeIn the more general case of
catch
vsorelse
, it is not as clear:This actually compiles, but is more ambiguous. In this case, parentheses should indeed be encouraged:
The text was updated successfully, but these errors were encountered: