Idiomatic Go Question
Idiomatic Go Question
Given the following short function
go
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
go
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!