Given the following short function
func example(foo string) error {
if bar, err := doSomething(foo); err != nil {
return err
} else {
doSomethingElse(bar)
}
return nil
}
Why does the linter recommend I change the if block to
var bar whateverType
if bar, err = doSomething(foo); err != nil {
return err
}
doSomethingElse(bar)
return nil
}
In my mind the former example restricts the bar variable to the smallest scope that is needed, and more clearly identifies doSomethingElse as something that should only happen if err != nil.
I know it’s redundant, but now if I want to change it to an else if ... chain I don’t have to worry about accidentally including or excluding code from that block, I already know exactly what’s supposed to be in it. I just feel like it’s a safer programming practice.
But looking forward to other opinions and discussion. Thanks!


Coming from C (with MISRA and flexelint) I also thought this idiom was a bit ‘ick’ in Go… but I guess they feel a return in an if-block makes the else redundant.
I was taught (again, in C/C++) that one should strive for single return points in functions, so actually either of these forms bug me to some extent.
In Go one can name the return variable(s) in the func declaration line, eg.
…but that’s not ‘idiomatic’ Go either :)