golang/go

proposal: add functionality to remove repetitive if err != nil return

losjr opened this issue · 5 comments

losjr commented

Great language but kind of tired of writing:

if( err != nil ){
return PrimaryData{}, err
}

Proposing something similar to 'defer' except with a condition where you declare the statement after the variable is defined. Using 'try' in the example but feel free to replace 'try' with your favorite exception handler like 'rescue' et al. If the condition in the 'try' is true the block executes. Currently, thinking the block should always have a return so it only executes once. Thinking the statement should be treated as if the compiler inserted it after every assignment of the variable(s) in the condition

func repeatErrReturn() (out User, err error) {
try( err != nil ){
   return User{}, err
}
... // real code
yeahRight , err = otherPkg.unreliable()
.. // more code
}

or

func repeatErrReturn2() (interface{},  error) {
var err
try( err != nil ){
   return User{}, err
}
... // real code
_ , err = otherPkg.buggy()
.. // more code and other 'err' assignments
}

This and similar ideas have been discussed many times in the past. Here is a recent discussion: https://groups.google.com/d/msg/golang-nuts/UwH5CreZPe4/xxI8gFsVBAAJ .

Make sure to read https://blog.golang.org/errors-are-values .

In languages such as snobol, icon and unicon, you could return from a function in a special way to indicate error or failure, and any such failure return would be automatically propagated recursively op the call stack unless the failure value is received as an additional return value. This would involve a new keyword, say "failure" for such a fail return.

But I realise that this is probably too "magical" for Go. Still, it is a useful feature in a higher level language.

losjr commented

@ianlancetaylor , Thanks for the article and the group link. The blog has a good point about how to use the language to minimize my stated annoyance.

pciet commented

I think the error type needs to be used in currently uninvented ways before a new decenter error handling pattern would emerge.

adg commented

I don't think this is in the spirit of the language, and has been hashed out many times before. While there is probably room for a detailed proposal in this area, I'm declining this particular one.