In this example we are going to exit forever loop and carry on to next steps outside of the loop instead of terminating the whole process.


Application


This example loops forever and never gets to fmt.Println("main: end") line. If you used os.Exit(0) after fmt.Println("timeout") it would exit the application straightaway.


package main

import (
"fmt"
"time"
)

func main() {
fmt.Println("main: start")

for {
select {
case <-time.After(2 * time.Second):
fmt.Println("timeout")
}
}

fmt.Println("main: end")
}

main: start
timeout
timeout
timeout
timeout
...
...

Solution 1


This is the preferred solution which is based on Labels.


package main

import (
"fmt"
"time"
)

func main() {
fmt.Println("main: start")

Loop:
for {
select {
case <-time.After(2 * time.Second):
fmt.Println("timeout")
break Loop
}
}

fmt.Println("main: end")
}

main: start
timeout
main: end

Solution 2


This uses an anonymous function/closure.


package main

import (
"fmt"
"time"
)

func main() {
fmt.Println("main: start")

func() {
for {
select {
case <-time.After(2 * time.Second):
fmt.Println("timeout")
return
}
}
}()

fmt.Println("main: end")
}

main: start
timeout
main: end