Two quick related notes: I missed a day or two last week, due to travel. I’lll be traveling through the middle of next week as well, so these “daily” emails may be slightly less frequent. We’ll see.
And related to that, no live stream this week or next. I expect to live stream again July 8. Hope to see you then!
For statements with
range
clause…
- For channels, the iteration values produced are the successive values sent on the channel until the channel is closed. If the channel is
nil
, the range expression blocks forever.
First, recall that when ranging over a channel, we have at most a single iteration variable. If we attempt to initialize two iteration variables, we’ll get a compilation error:
var ch chan int
for x, y := range ch { // range over ch (variable of type chan int) permits only one iteration variable
The value assigned to the single iteration variable is the next value read from the channel, and has the same type as the channel’s element type.
var ch chan int
for x := range ch { // Blocks until a value can be read, then is assigned to x with type int
If you attempt to range over a nil channel (as I actually do above), it will block forever.
What value is that?
I’m not aware of any actual utility of this charactaristic, other than the fact that it’s consistent.
If you try to read from an empty slice, you’ll get nothing. If keep retrying to read from that slice, until something is there, you’ll block until data is present. Blocking forever on a nil
channel, therefore, seems consistent with this behavior.
Are you aware of any actual utility in reading from a nil channel? If so, let me know!
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)