go语言---for

go语言---for

https://blog.csdn.net/cyk2396/article/details/78873930

执行以下代码,发现无法跳出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循环外")
}


解决办法有两个:

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:


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循环外")
}

分析:
结果
=for===
for循环内 i= 1
for循环内 i= 2
for循环内 i= 3
for循环内 i= 4
跳出循环SelectTest
for循环外
for循环内 i= 1
for循环内 i= 2
for循环内 i= 3
for循环内 i= 4
跳出for循环SelectTest1
for循环外
使用break lable 和 goto lable 都能跳出for循环;

  • 不同之处在于:

break标签只能用于for循环,且标签位于for循环前面,goto是指跳转到指定标签处

原文地址:https://www.cnblogs.com/Leo_wl/p/9269287.html