proposal: Go 2: new syntax for abbreviation of if err != nil { return ..., err }
#51146
Labels
error-handling
Language & library change proposals that are about error handling.
FrozenDueToAge
LanguageChange
Suggested changes to the Go language
Proposal
v2
An incompatible library change
Milestone
Author background
experienced
Related proposals
Has this idea, or one like it, been proposed before?
I can't find a precise searching keyword in GitHub issue. I have read some proposals which will list below
proposal: Go 2: introduce "then" keyword in if statement to allow one liner if statement for better error handling. #46717 , proposal: allow implicit conversion of error to bool in if statements, fmt on one line #38151 My proposal is more concise. It does not need to write
if
proposal: Go 2:
onErr
simple macro for common case error handling. A #32437 counter-proposal. #32946 My proposal applies to less scenarios but more clearDoes this affect error handling?
Yes
See above
Is this about generics?
No
Proposal
What is the proposed change?
One line introduce: Go will expand
some Function()?
to equivalentif err != nil { return ..., err }
An example from my demo https://github.com/lance6716/errhell
will be converted to
Who does this proposal help, and why?
Developer can write less code 😄
Please describe as precisely as possible the change to the language.
The new token
?
can only be legal appended to such a function call, name itfn
:fn
has one or more return values, and only one return value implementserror
interfacefn
has no more than one return values which implementserror
interfaceIf it's legal, the effect is equivalent to a
if
statement being inserted after the call offn
. The returned error offn
will be nil-checked, and there's a return statement in then-body to fill the return values of caller offn
with the error and/or zero values.I have made a demo: https://github.com/lance6716/errhell , the test input can be found in https://github.com/lance6716/errhell/blob/936cdcb459015fd5ce066b3f9b4325dcff6a8430/test/input/input.go and equivalent output can be found in https://github.com/lance6716/errhell/blob/936cdcb459015fd5ce066b3f9b4325dcff6a8430/test/expected/expected.go
What would change in the language spec?
Please also describe the change informally, as in a class teaching Go.
I think my demo and example is clear to explain it.
Is this change backward compatible?
No
Show example code before and after the change.
Orthogonality: how does this change interact or overlap with existing features?
No
Is the goal of this change a performance improvement?
No
Costs
No change if don't use it
compiling is a bit more complex?
I'm not sure about how they work, but they should be able to re-use the syntax
I'm not an expert 😢 But I think as my demo it only requires checking the current stack.
Only affects compiling
See my demo https://github.com/lance6716/errhell
https://github.com/lance6716/errhell
The text was updated successfully, but these errors were encountered: