英文:
Golang: Global vars scope and routines
问题
我正在尝试理解我在使用全局变量和例程时遇到的问题。
我创建了一个简化的测试案例来演示:
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)
}
它正确返回:
a _i 5
b _i 5
c _i 5
但是,如果我在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)
}
它返回:
a _i 5
b _i 5
c _i 0
有人能解释一下我在这里漏掉了什么吗?
谢谢
英文:
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
答案1
得分: 1
第二个程序在main()函数中使用短变量声明声明了局部变量_i。
匿名函数中的打印语句使用了main()函数中的局部变量。局部变量的值为5。update()函数中的打印语句使用了包级别的变量。包级别的变量的值为0。
通过在main()函数中对_i进行赋值来修复:
func main() {
    _i = 5 // <-- 在这一行中去掉冒号。
    fmt.Println("a _i", _i)
    go func() {
        fmt.Println("b _i", _i)
        update()
    }()
    ...
}
英文:
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()
    }()
    ...
}
答案2
得分: 0
在上一个版本中,你使用 _i := 5 来初始化 _i,:= 创建了一个新的 _i,它遮蔽了全局的 _i。这就是为什么 update() 打印出 0,因为全局的 _i 从未被设置过任何值。你可以将初始化改为 _i = 5 来修复这个问题。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论