
3

go语言for循环中的break
source link: https://segmentfault.com/a/1190000040507680
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

go语言for循环中的break
发布于 今天 16:23
今天遇到一个小坑,就是在for包裹的select中使用break,只会跳出select,不会跳出for循环,case如下:
func main() { cxt,cancel := context.WithCancel(context.Background()) var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() for { select { case <-cxt.Done(): time.Sleep(time.Second) fmt.Println("it cancel") break //只会跳出select 不会跳出for循环 //在这里可以直接return //或者配合label标签推出循环 default: fmt.Println("Go go go") time.Sleep(time.Second) } } }() time.Sleep(1500*time.Millisecond) cancel() wg.Wait() }
Go go go Go go go it cancel it cancel it cancel it cancel it cancel ··· //死循环
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK