此示例取自tour.golang.org/#63
package main
import (
"fmt"
"time"
)
func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}
func main() {
go say("world")
say("hello")
}
Run Code Online (Sandbox Code Playgroud)
hello
world
hello
world
hello
world
hello
world
hello
Run Code Online (Sandbox Code Playgroud)
为什么world只打印4时代而不是5?
编辑:答案可以引用golang规范:
程序执行从初始化主包然后调用main函数开始.当函数main返回时,程序退出.它不等待其他(非主要)goroutines完成.