Quit Channel
In this lesson, we'll study a pattern related to quitting from a select statement.
We'll cover the following...
You will notice that you have probably seen the quit channel pattern in the coding examples before. Let’s discover more about it!
So we’ll set up a car race competition. In the code below, we launch three goroutines by calling the Race
function in a for-loop. Now we are only interested in the race until one of the cars reaches the finishing line. Let’s see how it’s done:
Press + to interact
package mainimport ( "fmt""math/rand""time")func Race(channel, quit chan string, i int) {channel <- fmt.Sprintf("Car %d started!", i)for{rand.Seed(time.Now().UnixNano())time.Sleep(time.Duration(rand.Intn(500)+500) * time.Millisecond)quit <- fmt.Sprintf("Car %d reached the finishing line!", i)}}func main() {channel := make(chan string)quit := make(chan string)for i:=0; i < 3; i++{go Race(channel,quit,i)}for{select{case raceUpdates := <-channel:fmt.Println(raceUpdates)case winnerAnnoucement := <-quit:fmt.Println(winnerAnnoucement)return}}}
After the goroutines start concurrently, we have a select statement from line 27 to line 34.
for{
select{
case raceUpdates := <-channel:
...Access this course and 1400+ top-rated courses and projects.