IMO that’s less idiomatic Go, more just plain old clearly written code. Whenever possible, the nominal (non-error) path should stay at the same level of indentation. Indentation should be reserved (as much as is possible) for loops and atypical conditions (including errors).
Golang
This is a community dedicated to the go programming language.
Useful Links:
Rules:
- Posts must be relevant to Go
- No NSFW content
- No hate speech, bigotry, etc
- Try to keep discussions on topic
- No spam of tools/companies/advertisements
- It’s OK to post your own stuff part of the time, but the primary use of the community should not be self-promotion.
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.
func example(foo string) (e error) {
/* e is implicitly nil so far */
if bar, e := doSomething(foo); e != nil {
/* e was set above to non-nil */
} else {
doSomethingElse(bar)
}
return e /* or just 'return' */
}
...but that's not 'idiomatic' Go either :)
I can't speak for Go's maintainers, but your story fits a pattern I've noticed: The language, standard library, and toolchain are excessively prescriptive about how things should be done, while insufficiently considerate of diversity in people's needs. Ergonomics suffer because of it, as do other things that I find important.
Nit: I think you meant to write, "should only happen if err == nil."
@RemindMe@programming.dev 36 hours