在Go语言中,可以使用循环遍历通道发送的所有值,直到通道关闭。

huangapple go评论81阅读模式
英文:

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 (
	&quot;fmt&quot;
)

func pinger(c chan string) {
	for i := 0; i &lt; 3; i++ {
		c &lt;- &quot;ping&quot;
	}
	close(c)
}

func main() {
	var c chan string = make(chan string)

	go pinger(c)

	opened := true
	var msg string

	for opened {
		msg, opened = &lt;-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 (
    &quot;fmt&quot;
)

func pinger(c chan string) {
    for i := 0; i &lt; 3; i++ {
        c &lt;- &quot;ping&quot;
    }
    close(c)
}

func main() {
    var c chan string = make(chan string)

    go pinger(c)

    for msg := range c {
        fmt.Println(msg)
    }
}

huangapple
  • 本文由 发表于 2015年1月14日 06:34:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/27932752.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定