liveBook · Manning

Select statement

As explained in Go in Practice, Second Edition

A select statement is a language construct that retrieves selected data or chooses among alternative operations or cases according to the language's rules.

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

How Go in Practice, Second Edition covers it

How deep it goes
Explains readiness, waiting, default behavior, channel direction, and a complete timeout-driven echo implementation.
Examples
Uses a standard-input echo program that receives input through a channel and times out after thirty seconds.
What it assumes
Assumes basic goroutines and channels while clarifying channel creation, direction, sending, and receiving.
What you can do after
Build interruptible channel workflows that handle data events and timeout events in one control structure.
How it connects
Connects goroutines, channels, channel direction, time.After, and timeout signaling.

Also explained in

Compare how 9 books explain select statement →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.