I’ll be live streaming again today! But this time it’s a bit different.
I found a bug in the Go standard library! 😲
So on today’s live stream, I’ll be coming up with a minimal reproducible case, and filing a bug report. And hopefully also submitting a patch to fix the bug!
I recently asked you if you knew of any practical uses of a nil
channel in Go.
One reader wrote back to point me to a blog post by Francesc Campoy, that offers one possible use, which I think I can extend to a second, realted, possible uses.
Imagine you’re handling multiple channels. The blog post’s example is aggregating two channels into one, but there are many other reasons you may want to handle multiple channels. Here’s a simplified example. Read the blog post for the full explanation. 😊
for chanA != nil && chanB != nil{
select {
case value, ok := <- chanA:
if ok {
/* do something with value */
continue
}
chanA = nil
case value, ok := <- chanB:
if ok {
/* do something with value */
continue
}
chanB = nil
}
}
In short, it starts a for loop that runs until both chanA
and chanB
are nil
. Then it reads from both channels, and when it detects that one of the channels has been closed, it sets it to nil
, which in turn causes that select case to block forever; always deferring to the other.
I think this example could be simply extended to handle channels that are not yet ready, as well, as a second, related use case. But I’ll leave that implementation to the reader.
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)