英文:
why can not run go function in go?
问题
这是下面的代码:
func main() {
values := []int{1, 2, 3, 4}
for _, v := range values {
go func(x int) {
fmt.Println(x)
}(v)
}
}
如果这段代码没有go关键字,它将打印1, 2, 3, 4。
但是现在它无法打印任何代码,为什么?
go版本:1.5.2 darwin/amd64
英文:
This is the below code:
func main() {
values := []int{1, 2, 3, 4}
for _, v := range values {
go func(x int) {
fmt.Println(x)
}(v)
}
}
If this code have not go keyword, it will print 1, 2, 3, 4.
But it can not print any code now, why?
go version: 1.5.2 darwin/amd64
答案1
得分: 2
简短的翻译:在最后加上一个等待语句,它将会打印出来。
更好的选择是通过通道来进行终止通信。
长篇的翻译:一个Go程序的生命周期与主goroutine的生命周期相同。
当你执行go somefunc()时,它不会立即启动,而是将somefunc() 调度起来。
在你的情况下,你调度了一些goroutine并退出 - 没有理由让调度器运行其他的goroutine。
英文:
Short: Place a wait at the end and it will print.
Better option: communicate termination via channels.
Long: A go program lives as long as the main goroutine lives.
When you do go somefunc(), it's not started immediately, the somefunc() gets scheduled.
In your case you schedule some goroutines and quit – and there's no reason for the scheduler to run other goroutines.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论