select statement is used to multiplex channels, allowing any ready alternative to proceed among:
func main() {
chans := []chan int{
make(chan int),
make(chan int)
}
for i := range chans {
go func(i int, ch chan<- int) {
for {
time.Sleep(time.Duration(i)*time.Second)
ch<- i
}
}(i+1, chans[i])
}
for i := 0; i < 12; i ++ {
// Select allows us to listen to both channels at the same time, and whichever
// one is ready first will be read
select {
case m0 := <-chans[0]:
fmt.Println("received", m0)
case m1 := <-chans[1]:
fmt.Println("received", m1)
}
}
}
time.After functiontime.After(5*time.Second) will create a new timer, this timer has a channel which is returned by this function. The timer will send the current time on this channel when the timer elapsestime.Ticker which is similar but will tick indefinitely with a given tick ratedefault case is already and is chosen if no other case is readyfunc sendOrDrop(data []byte) {
select {
case ch <- data;
// sent ok; do nothing
default:
log.Printf("overflow, dropped %d bytes", len(data))
}
}