What I Don't Like in Go

Interesting read. My biggest gripe is shorthand assignment :=

For example, this is an error in Go:

var err = DoThing()
if err == nil {
	return err
}
var data, err = ReadFile() // compile error: `err` is already declared
data, err := ReadFile() // but this is fine

I wish there was a way to say, “I’d like to declare new variable data but re-use existing variable err without re-declaring it” in a single assignment statement. Then, you could eliminate := assignment and just use var everywhere. My gripe with := is it says, “I don’t care if this variable exists already or not. If it does, use it; otherwise, I’m declaring it now.” IMO, it feels safer to be more explicit about which variables are newly declared and which you intend to re-use.

1 Like