3 ms·
The behaviour you are talking about isn't anything to do with :=. It's just how scoping works in Go. := is just syntactic sugar. http://play.golang.org/p/bh6pm
by echlebek 11y ago
The behaviour you are talking about isn't anything to do with :=. It's just how scoping works in Go. := is just syntactic sugar.
http://play.golang.org/p/bh6pm_8s9S http://play.golang.org/p/bh6pm_8s9S
- YZF 11y agoProbably the root of the issue is that it's slightly more complicated than syntactic sugar: "Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block (or the parameter lists if the block is the function body) with the same type, and at least one of the non-blank variables is new. As a consequence, redeclaration can only appear in a multi-variable short declaration. Redeclaration does not introduce a new variable; it just assigns a new value to the original." I.e. the mix of declaration with re-declaration. I agree it doesn't seem like much but it ends up causing needless confusion. If there was a more explict way of doing this, e.g.: x, var y = 1, 2 // y explicitly declared maybe that would be better. not sure.
- bkeroack 11y agoThis is what enables the idiom "foo, err := DoSomething()" where err is declared previously. Without the mixed declaration/redeclaration you'd have to either declare a different error variable every time in the block, or explicitly declare your result variable: foo1, err1 := DoSomething() foo2, err2 := DoSomething2() // or var Foo foo var err error foo, err = DoSomething() foo, err = DoSomething2()