💻 Tech
In Go, break can have labels to break out of specific loops. The example below uses for with select statement inside it. The select statement waits for three channels: a sigChan for os.Signal, a timeout after 1 minute, and a done channel to signal the end of the program. The goal is to break the for loop once done is signaled.
// let's say this is updated somewhere in the program
done := make(chan bool, 1)
timeout := time.After(1 * time.Minute)
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
forLoop:
for {
select {
case <-sigChan:
fmt.Println("Received signal")
// some action here
case <-timeout:
fmt.Println("Timeout")
// some action here
case <-done:
fmt.Println("Done")
// exit the for loop
// with break without label, it would only exit the select statement and let the for loop continue
break forLoop
}
}