[Solved] Select statement channel example


The select statement chooses a case whose communication op would not block. If there are multiple cases whose comm. op would not block, one is chosen randomly.

Since in the example all communication ops would block, and since a default is provided, that will be executed.

To “trigger” another case, you have to make sure its comm. op does not block. In the example no one is sending or receiving anything from any of the channels that are used in the cases. Hell, they are not even initialized. And both sending to and receiving from a nil channel blocks forever (for details see How does a non initialized channel behave?). So you should do that: initialize a channel and send to / receive from it, the one whose case you want to trigger. For example:

c1 = make(chan int, 1)
c1 <- 1

This snippet initializes the c1 channel with a buffer of 1, and sends a value on it. So in the select statement after this the communication operation i1 = <-c1 would not block, so this will be chosen, and the output will be:

received  1  from c1

Try it on the Go Playground. (Note: I changed all Printf() calls to Println().)

Note that sending on / receiving from channels could happen concurrently, on other goroutines. I chose a buffered channel and the same goroutine for simplicity, and so that it behaves as you’d expect it even on the Go Playground.

More about channels: What are golang channels used for?

1

solved Select statement channel example