For-Select loop in Go

Simple break in for-select loop, will not break out of for loop. You should use break label.

demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package main

import (
"fmt"
"time"
)

func main() {

one := time.After(time.Second * 2)
two := time.After(time.Second * 4)
three := time.After(time.Second * 6)

out:
//fmt.Println("out of for") // anything here will invoke error
for {
fmt.Println("head")
select {
case <-one:
fmt.Println("one")
continue

case <-two:
fmt.Println("two")
break

case <-three:
fmt.Println("three")
break out

}
fmt.Println("tail")
}
//out: // break label must define before for loop
fmt.Println("in the end")
}

Playground

more

Break statement