I'm trying to understand a problem I have using a global var and a routine. I created a simplifed test case to demonstrate:
var _i int = 5
func main() {
fmt.Println("a _i", _i)
go func() {
fmt.Println("b _i", _i)
update()
}()
...
}
func update() {
fmt.Println("c _i", _i)
}
It correctly returns
a _i 5
b _i 5
c _i 5
But if I initialise my var inside main:
var _i int
func main() {
_i := 5
fmt.Println("a _i", _i)
go func() {
fmt.Println("b _i", _i)
update()
}()
...
}
func update() {
fmt.Println("c _i", _i)
}
It returns
a _i 5
b _i 5
c _i 0
Anybody can explain what I'm missing here? Thanks
CodePudding user response:
The second program declares local variable _i in main() using a short variable declaration.
The print in the anonymous function uses the local variable in main(). The local variable has value 5. The print in the update() function uses the package-level variable. The package-level variable has value 0.
Fix by assigning to _i in main():
func main() {
_i = 5 // <-- colon removed from this line.
fmt.Println("a _i", _i)
go func() {
fmt.Println("b _i", _i)
update()
}()
...
}
CodePudding user response:
In the last version you initialized _i with _i := 5 the := creates a new _i that shadows the global one. This is why update() prints 0, the global _i was never set to anything. You can change your initialization to _i = 5 to fix this.
