Skip to content

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

Closed
@losjr

Description

@losjr

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
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeLanguageChangeSuggested changes to the Go languageProposalerror-handlingLanguage & library change proposals that are about error handling.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions