proposal: Go 2: syntactic sugar for error handling (sharp guard) #57052
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
if err != nil { ... }
Related proposals
Proposal
It's rather simple, helps to reduce repeated code, and seems back-compatible
I'm not sure I'm able to give detailed specs, but I'll just show a simple example
# ...
syntax mean? It can appears only on the left side of operators=
and:=
. When it gets an errorerr
(it probably can get not only error, I'll write about it below), it checks whethererr
isnil
. If it is, it works just like_
. But if it's not, function returns the values given in parenthesis. If function return only one value, parenthesis are optional, so if the only return value has typeerror
, error handling can be as simple asfile, #_ := os.Create("some-file")
. If function returns no value, probably it should look like#()
.Let's call this syntax sharp guard
The underline
_
inside #-guard is the value passed from the right side of an expression. Probably, we should choose another special sign or keyword for it to escape a confusion with underline used to ignore a valueKeep in mind, sharp guards can take any expressions as well. Also it's reasonable to provide "partial" sharp guard syntax when return values are named. So, this code may become possible:
Probably,
#panic(...)
here is a special case. It can be used in functions with any number of return valuesProbably, boolean must be an exception, but in my opinion using error as the only type for sharp guards is the most solid decision.
Costs
I don't really understand the costs well. Participating in this discussion is welcome.
The text was updated successfully, but these errors were encountered: