Range Over Channels in Julia

# We'll iterate over 2 values in the `queue` channel.
queue = Channel{String}(2)
put!(queue, "one")
put!(queue, "two")
close(queue)

# This `for` loop iterates over each element as it's
# received from `queue`. Because we closed the
# channel above, the iteration terminates after
# receiving the 2 elements.
for elem in queue
    println(elem)
end

In Julia, we use Channel to create a channel. The Channel{String}(2) creates a channel that can hold up to 2 String values.

We use put! to send values into the channel, which is equivalent to the <- operator in the original example.

The close function is used to close the channel, signaling that no more values will be sent.

Julia’s for loop can iterate directly over a channel, similar to the range keyword in the original example. This will continue until the channel is closed and empty.

To run this program:

$ julia range_over_channels.jl
one
two

This example also demonstrates that it’s possible to close a non-empty channel but still have the remaining values be received.

In Julia, channels provide a way to pass messages between tasks (coroutines), which are Julia’s lightweight threads. This concept is similar to goroutines in the original language, allowing for concurrent programming.