Skip to content

Select

In Go, the select statement is used with channels to handle multiple concurrent operations. It allows you to wait on multiple channel operations, making it easier to manage goroutines and synchronize their actions.

Sending via 2 channels

package main
import (
"fmt"
"time"
)
func main() {
ch1 := make(chan int)
ch2 := make(chan int)
go func() {
time.Sleep(time.Second * 2)
ch1 <- 1
}()
go func() {
time.Sleep(time.Second)
ch2 <- 2
}()
for range 2 {
select {
case first := <-ch1:
fmt.Print(first)
case second := <-ch2:
fmt.Print(second)
}
}
}

Example: Web Scraper with Timeout and Multiple Sources

Imagine we want to scrape data from multiple websites concurrently. We’ll use channels to manage results and errors, along with a timeout for each request.