Home
Go
select and chan Example
Updated Jan 12, 2025
Dot Net Perls
Select, chan. Suppose we have one or more goroutines running, and they are sending the results of their computations over channels. We can use the select block to receive these results.
chan
Though it is possible to use goroutines without select, this construct makes receiving values in a complicated program easier. We can use select within a for-loop to receive all values.
Example. This program uses 2 channels that send ints back (the chan int type is used). In the select statement, we receive the values sent from within those goroutines.
Part 1 We create two channels that are used in the goroutines (go funcs) that are specified next in the program.
make
Part 2 This goroutine uses the "go func" keywords and receives an int, and has 2 send statements where it sends values onto the first channel.
Part 3 This goroutine is similar to the previous one, but it uses the second channel instead of the first.
Part 4 We sleep our main thread. This is important so that the goroutines can start up and send some values before the program exits.
Part 5 We use a for-loop to loop infinitely until a break keyword (found in the select default case) is reached.
for
Part 6 The select statement tries to receive a value from the channels specified in the cases. If nothing is received, it runs the default case.
package main import ( "fmt" "time" ) func main() { // Part 1: make a couple channels that send ints. c := make(chan int) c2 := make(chan int) // Part 2: use this goroutine to accept 1 argument and send 2 ints. go func(x int) { c <- 222 + x c <- 500 + x }(1) // Part 3: use (and call) another goroutine that acts on the second channel. go func(x int) { c2 <- 555 + x c2 <- 1000 + x }(1) // Part 4: sleep, as we need to be sure the goroutines have run. time.Sleep(10000) // Part 5: continue looping until no more channel activity. for { r := 0 // Part 6: use select to receive results from channels, and handle default case where nothing is happening. select { case r = <-c: fmt.Println("RESULT FROM CHAN: ", r) case r = <-c2: fmt.Println("RESULT FROM CHAN2: ", r); default: fmt.Println("END") return } } }
RESULT FROM CHAN2: 556 RESULT FROM CHAN: 223 RESULT FROM CHAN: 501 RESULT FROM CHAN2: 1001 END
Summary. The select statement is a critical component to using goroutines in the Go language. It makes receiving values from channels easier and we can merge all results with it.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 12, 2025 (new).
Home
Changes
© 2007-2025 Sam Allen