原标题:golang 跳出for循环

执行以下代码,发现无法跳出for循环:

func SelectTest() {
	i := 0
	for {
		select {
		case <-time.After(time.Second * time.Duration(2)):
			i++
			if i == 5 {
				fmt.Println("跳出for循环")
			}
		}
		fmt.Println("for循环内 i=", i)
	}
	fmt.Println("for循环外")
}

解决办法有两个:来源地址:https://www.yii666.com/blog/35884.html

1.使用break:

func SelectTest() {
	i := 0
Loop:
	for {
		select {
		case <-time.After(time.Second * time.Duration(2)):
			i++
			if i == 5 {
				fmt.Println("跳出for循环")
				break Loop
			}
		}
		fmt.Println("for循环内 i=", i)
	}

	fmt.Println("for循环外")

}

2.使用goto:地址:https://www.yii666.com/blog/35884.html文章来源地址:https://www.yii666.com/blog/35884.html

文章地址https://www.yii666.com/blog/35884.html

func SelectTest() {
	i := 0
	for {
		select {
		case <-time.After(time.Second * time.Duration(2)):
			i++
			if i == 5 {
				fmt.Println("跳出for循环")
				goto Loop
			}
		}
		fmt.Println("for循环内 i=", i)
	}
Loop:
	fmt.Println("for循环外")
}

分析:文章来源地址https://www.yii666.com/blog/35884.html

使用break lable 和 goto lable 都能跳出for循环;不同之处在于:break标签只能用于for循环,且标签位于for循环前面,goto是指跳转到指定标签处