A select statement coordinates channel communication when a goroutine must receive data while remaining interruptible. It waits until a channel operation is ready, then executes the matching case; a default case can provide nonblocking behavior. section 5.3.1
An idiomatic channel-based workflow uses select to:
- Watch multiple channels in one control flow. section 5.3.1
- Receive echoed input from a channel and write it to standard output. section 5.3.1
- Interrupt waiting after time.After sends a timeout event. section 5.3.1
Listing 5.6 Using channels
package main
import (
"fmt"
"os"
"time"
)
func main() {
echo := make(chan []byte) #1
go readStdin(echo) #2
for {
select { #3
case buf := <-echo: #4
os.Stdout.Write(buf)
case <- time.After(30 * time.Second): #5
break #5
} #5
} #5
} #5
func readStdin(out chan<- []byte) { #6
for { #6
data := make([]byte, 1024) #6
l, _ := os.Stdin.Read(data) #6
if l > 0 {
out <- data #7
}
}
}
A complete Go echo program combines a goroutine, a bidirectional channel, a receive case, and a time.After case to stop waiting after 30 seconds. section 5.3.1








