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
>Solution :
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.