The range
a keyword can be used to iterate over the values received from a channel. The iteration stops when the channel is closed or has no more values to receive.
Here’s an example to demonstrate the use of range
with channels:
package main
import "fmt"
func main() {
queue := make(chan int, 5)
queue <- 1
queue <- 2
queue <- 3
close(queue)
for value := range queue {
fmt.Println(value)
}
}
This program creates a channel queue
of size 5, sends values 1, 2, and 3 into it, then closes the channel. The for
loop then iterates over the channel and prints each received value. The output will be:
1
2
3
Here’s an example of range over channels:
package main
import "fmt"
func main() {
queue := make(chan string, 2)
queue <- "one"
queue <- "two"
close(queue)
for elem := range queue {
fmt.Println(elem)
}
}
In the example, we create a buffered channel queue
with capacity 2. We send two string values "one"
and "two"
into the channel. Then, we close the channel using the close
function. In the for loop, we range over the channel queue
, printing each element until the channel is closed and empty. The output will be:
one
two
Leave a Reply