Range Over Channels in Crystal
In Crystal, we use channels to achieve similar functionality to Go’s channels. Here’s how the code works:
We create a buffered channel of strings with a capacity of 2 using
Channel(String).new(2)
.We send two values, “one” and “two”, to the channel using the
send
method.We close the channel using the
close
method.We use the
each
method to iterate over the values in the channel. This is equivalent to therange
iteration in the original example.Inside the
each
block, we print each element received from the channel.
When you run this program, it will output:
This example also demonstrates that it’s possible to close a non-empty channel but still have the remaining values be received. In Crystal, just like in the original example, closing the channel doesn’t immediately discard the buffered values. The each
method will continue to receive values until the channel is empty, even if it has been closed.
Crystal’s syntax and channel behavior are very similar to Go’s in this case, making the translation quite straightforward. The main differences are in the method names (send
instead of <-
for sending, each
instead of range
for iterating) and the channel creation syntax.