How can I explicitly empty a channel?

Toad picture Toad · Oct 1, 2014 · Viewed 23.8k times · Source

The short version: Is there a way to empty a go channel without recreating it, or looping through it?

The why: I'm using two channels to send and receive data, and I have an extra channel to signal that a reconnect is needed.

Now when the transport has been reset/reconnected I want to 'empty' the extra channel to make sure that there is not any lingering other reset requests which would cause the thing to reconnect again.

Answer

Simon Fox picture Simon Fox · Oct 1, 2014

It is not possible to empty a channel without a loop. If you don't have any concurrent receivers, then you can use this simple loop:

for len(ch) > 0 {
  <-ch
}

If you do have concurrent receivers, then use the loop:

L:
for {
    select {
    case <-c:
    default:
       break L
    }
}