12/01/2020 - GO
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.
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
...
...
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
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