一、goroutine
package mainimport ("fmt""time"
)func main() {//用go创建承载一个形参为空,返回值为空的一个函数go func() {defer fmt.Println("A.defer")func() {defer fmt.Println("B.defer")//退出当前goroutinefmt.Println("B")}()fmt.Println("A")}()//死循环for {time.Sleep(1 * time.Second)}}
二、退出方式
1、return
package mainimport ("fmt""time"
)func main() {//用go创建承载一个形参为空,返回值为空的一个函数go func() {defer fmt.Println("A.defer")returnfunc() {defer fmt.Println("B.defer")//退出当前goroutinefmt.Println("B")}()fmt.Println("A")}()//死循环for {time.Sleep(1 * time.Second)}}
2、用runtime.Goexit()
package mainimport ("fmt""runtime""time"
)func main() {//用go创建承载一个形参为空,返回值为空的一个函数go func() {defer fmt.Println("A.defer")//returnfunc() {defer fmt.Println("B.defer")//退出当前goroutineruntime.Goexit()fmt.Println("B")}()fmt.Println("A")}()//死循环for {time.Sleep(1 * time.Second)}}
三、传入一个形参
package mainimport ("fmt""time"
)func main() {//用go创建承载一个形参为空,返回值为空的一个函数//go func() {// defer fmt.Println("A.defer")// //return// func() {// defer fmt.Println("B.defer")// //退出当前goroutine// runtime.Goexit()// fmt.Println("B")// }()// fmt.Println("A")//}()//传入一个有参数的go func(a int,b int) bool {fmt.Println("a = ",a,"b = ",b)return true}(10,20)//死循环for {time.Sleep(1 * time.Second)}}