英文:
Iterate over all the values a channel sends until it is closed in Go
问题
我正在尝试理解goroutines和channels的工作原理。我有一个循环将值发送到一个channel,并且我想迭代所有channel发送的值,直到它关闭。
我在这里写了一个简单的示例:
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)
}
}
这会得到预期的结果,但我想知道是否有更简洁的方法来实现这个。
非常感谢你的帮助。
英文:
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
答案1
得分: 32
你可以在通道上使用range
。循环将一直持续到通道关闭,就像你想要的那样:
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)
}
}
英文:
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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论