Go语言 之Goexit
package main import ( "fmt" "runtime" ) func main() { go func() { defer fmt.Println("defer A") func() { defer fmt.Println("defer B") //结束goroutine runtime.Goexit() fmt.Println("B") }() fmt.Println("A") }() //保证main不结束执行 for { } //执行结果: //defer B //defer A }
调用 runtime.Goexit() 将立即终止当前 goroutine 执⾏,调度器确保所有已注册 defer延迟调用被执行。