2 ms·
If I were in charge of go, I would add some compiler magic and allow foo := bar() onError(err) { return nul, errors.New(“bar failed”, err) } as (almos
by Someone 4y ago
If I were in charge of go, I would add some compiler magic and allow
foo := bar() onError(err) {
return nul, errors.New(“bar failed”, err)
}
as (almost; difference would be the scope of ‘err’) shorthand for
foo, err := bar()
if err ≠ nil {
return nil, errors.New(“bar failed”, err)
}
I also would allow a short-hand version for single statement blocks:
foo := bar() onError(err) return nil, errors.New(“bar failed”, err)
That, IMO, keeps the spirit of (relative to, for example, JVM stack traces and try/catch) being in control of error reporting at the price of having to do more work getting decent partial stack trace-like information out of errors, but also removes a few pain points:
- it’s shorter (especially the single-line version)
- it limits the lifetime of ‘err’ to the ‘onError’ statement.
It also, IMO, reads easier than these proposals.
An implicitly declared ‘err’, as in
foo := bar() onError return nil, errors.New(“bar failed”, err)
would be even shorter, but IMO would be a bit too magical for go, even if we made it clear magic is happening by giving that variable a special name, as shell does with ‘$?’.