Closed
Description
Proposal: "onerr return"
Edit: Originally this was or return
, but I like onerr return
better since it's more explicit about what we're doing and why.
Current syntax:
func (this *ReaderThing) readBytesFromFile(filename string, maxBytes int) (bytesRead int, err error) {
f, err := os.Open(filename)
if err != nil {
return 0, err
}
...
}
Proposed syntax:
func (this *ReaderThing) readBytesFromFile(filename string, maxBytes int) (bytesRead int, err error) {
f, err := os.Open(filename) onerr return 0, err
...
}
Basically, if the last thing returned by a function is an error type, onerr
checks if it's null, and if not, runs the statement return 0, err
.
Specifically:
- The compiler makes sure that
onerr
can only follow a function that returns typeerror
as its last return value. - The result of
os.Open()
is stored tof, err
as normal. onerr
examines the last returned value of the function call (which must be typeerror
), and executes the subclause if it is not nil.- The
return
statement executed with theonerr
clause follows standard scoping rules, which means thaterr
is visible to it (as aref
andfilename
andmaxBytes
). err
has already been assigned to by the time theonerr
clause executes, and is visible due to scoping rules, so it's perfectly valid to access. There's nothing new or magical here.
Edit:
As an alternative (but only if we can be sure this won't break things or induce too much cognitive load) Allow block statements:
err := DoSomething() onerr {
fmt.PrintF("We got error %v\n", err)
do other stuff...
}