I really don’t know where to begin. I’ve looked on google, but nothing. I am just playing around with Channels trying to grasp the select{} feature. console returns: invalid character ‘F’ looking for beginning of value
What is the reason for all the 0’s continuing to print at execution despite all the channels being closed? I thought that was the signal that there was no more values to pull.
Is there a way to have end without setting a condition in the for loop?
A closed channel still sends the zero value so that consuming the channel can be used to “test” whether it’s open or not. You can implement this test by using the following constructions: msg, ok = <-c and checking “ok”, see Go Playground - The Go Programming Language
EDIT: The “done” channel solution is probably suboptimal in this case, because there are non-deterministically some number of "0"s at the end (I’ve seen 0, 1, and 2, but I think theoretically, depending on when select decides to pick the “done” channel, it could be any number?), based on whether the select grabs the “closing” channels. Best to stick with the “test” for closeness.
Also sorry this was bothering me, I realized after commenting that “returning” when a channel closed was incorrect in my implementation. Because there are two channels, the earlier solution might prematurely exit while the other channel is open (unlikely in this case but still technically wrong).
Here’s a more correct (though admittedly more complex) solution: Go Playground - The Go Programming Language, which only leaves the for loop after it confirms each channel is closed
That is very interesting. I appreciate you sending me multiple examples. So it appears a condition is necessary in the for loop in order for the program to execute properly.
Yeah, even if you ignore the parallel/concurrent stuff and just focus on the for loop, if it has no conditions defined (i.e. it’s just for { some stuff }), unless there is a break/return in the body, it’ll loop forever.