The select keyword
A select
statement in Go is like a switch
statement for channels and allows a goroutine to wait on multiple communication operations. Therefore, the main advantage you get from using the select
keyword is that the same function can deal with multiple channels using a single select
statement! Additionally, you can have nonblocking operations on channels.
The name of the program that will be used for illustrating the select
keyword will be useSelect.go
and will be presented in five parts. The useSelect.go
program allows you to generate the number of random you want, which is defined in the first command-line argument, up to a certain limit, which is the second command-line argument.
The first part of useSelect.go
is the following:
package main import ( "fmt" "math/rand" "os" "path/filepath" "strconv" "time" )
The second part of useSelect.go
is the following:
func createNumber(max int, randomNumberChannel chan<- int, finishedChannel chan bool) ...