select里面的break是无法退出for语句的。如下;
package main
import (
"fmt"
)
func main() {
var c=make(chan int,1024)
quit:=make(chan string,1)
c<-1
quit<-"q"
for{
select{
case <-c:
fmt.Println("here")
case <-quit:
fmt.Println("quit")
break
}
}
}
有几种方法可以退出for循环
1使用goto语句:
package main
import (
"fmt"
)
func main() {
var c=make(chan int,1024)
quit:=make(chan string,1)
c<-1
quit<-"q"
for{
select{
case <-c:
fmt.Println("here")
case <-quit:
fmt.Println("quit")
goto forEnd
}
}
forEnd:
}
2使用break标签
package main
import (
"fmt"
)
func main() {
var c=make(chan int,1024)
quit:=make(chan string,1)
c<-1
quit<-"q"
forEnd:
for{
select{
case <-c:
fmt.Println("here")
case <-quit:
fmt.Println("quit")
break forEnd
}
}
}
3使用return语句
package main
import (
"fmt"
)
func main() {
var c=make(chan int,1024)
quit:=make(chan string,1)
c<-1
quit<-"q"
some(c, quit)
fmt.Println("end")
}
func some(c1 chan int,c2 chan string) {
for{
select{
case <-c1:
fmt.Println("here")
case <-c2:
fmt.Println("quit")
return
}
}
}
有疑问加站长微信联系(非本文作者)