Reputation:
I created a channel and want to discharge it without using received values. However, compiler doesn't allow me to write code like this:
for i := range ch {
// code
}
complains that i is unused
substituting _ for i doesn't work either
What is the idiomatic way to do it?
Upvotes: 2
Views: 117
Reputation: 6966
You could use select
instead of range
:
for {
select {
// read and discard
case <-ch:
// to avoid deadlock
default:
continue
}
}
But then again, are you sure you really need the channel if you're not reading from it?
Upvotes: 2
Reputation: 12875
If you don't want to stuck in infinite loop read values until channel is not empty:
exitLoop:
for {
select {
case <-ch:
default:
break exitLoop
}
}
Demo: https://play.golang.org/p/UsIqdoAGZi
If you need "updatable channel" - which keeps only 1 last value, you may use this recipe - https://stackoverflow.com/a/47107654/5165332
Upvotes: 0