Range over Channels
This Go code demonstrates how to use a buffered channel and the range
keyword to iterate over the elements in a closed channel. Let's go through it with inline comments:
Output
Explanation:
package main
: Indicates that this Go file belongs to the main executable package.import "fmt"
: Imports the "fmt" package for formatting and printing.func main() { ... }
: The main function, where the execution of the program begins.queue := make(chan string, 2)
: Creates a buffered channel named 'queue' with a capacity of 2.queue <- "one"
: Sends the string "one" to the 'queue' channel.queue <- "two"
: Sends the string "two" to the 'queue' channel.close(queue)
: Closes the 'queue' channel to indicate that no more elements will be sent.for elem := range queue { fmt.Println(elem) }
: Uses therange
keyword to iterate over the elements in the closed 'queue' channel. The loop will exit when all elements have been received. In this case, it prints "one" and "two" because these elements were sent to the channel before it was closed.
Note: Closing a channel is important when the sender wants to signal that no more values will be sent. This is especially useful when using range
to iterate over a channel, as it allows the loop to exit when all values are received.
Last updated
Was this helpful?