I am trying to understand how goroutines and channels work. I have a loop sending values to a channel and I'd like to iterate over all the values the channel sends until it is closed.
I have written a simple example here:
package main
import (
"fmt"
)
func pinger(c chan string) {
for i := 0; i < 3; i++ {
c <- "ping"
}
close(c)
}
func main() {
var c chan string = make(chan string)
go pinger(c)
opened := true
var msg string
for opened {
msg, opened = <-c
fmt.Println(msg)
}
}
This gives the expected result but I'd like to know if there is a shorter way of doing this.
Many thanks for your help
You can use the range
over the channel. The loop will continue until the channel is closed as you want:
package main
import (
"fmt"
)
func pinger(c chan string) {
for i := 0; i < 3; i++ {
c <- "ping"
}
close(c)
}
func main() {
var c chan string = make(chan string)
go pinger(c)
for msg := range c {
fmt.Println(msg)
}
}