Search⌘ K
AI Features

The For-Select Loop

Explore how to implement the for-select loop in Go to manage multiple channels concurrently. Understand its use in infinite loops that listen for signals and process iterative data, enabling more effective concurrency patterns.

We'll cover the following...

The for-select loop can be structured as follows:

Go (1.6.2)
for { //either range over a channel or loop infinitely
select {
//handle channel operations
}
}

First, let’s try to loop over something that goes on infinitely.

Go (1.6.2)
package main
import "fmt"
func getNews(newsChannel chan string){
NewsArray := [] string {"Roger Federer wins the Wimbledon","Space Exploration has reached new heights","Wandering cat prevents playground accident"}
for _, news := range NewsArray{
newsChannel <- news
}
newsChannel <- "Done"
close(newsChannel)
}
func main() {
myNewsChannel := make(chan string)
go getNews(myNewsChannel)
for {
select{
case news := <-myNewsChannel:
fmt.Println(news)
if news == "Done"{
return
}
default:
}
}
}
...