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?
Try this:
package main
import (
"fmt"
)
func main() {
ch := make(chan int)
close(ch)
for range ch {
fmt.Println("for")
}
fmt.Println("done")
}
output:
done
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?
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