如何从Go通道中获取(并忽略)一个值

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

How to get (and ignore) a value from Go channel

问题

我在select语句中有以下代码。finish的类型是bool。实际上,我并不关心它的值,只要我能接收到任何东西就可以了。然而,Go会给我一个未使用的变量错误。我该如何解决这个问题?

case finish := <- termSig:

我目前的解决方法是使用Println(finish)

我尝试过:

case _ := <- termSig:

但这也不起作用。

英文:

I have the following code in a select statement. finish is of type bool. Actually, I don't even care of the value as long as I just receive anything. However, Go gives me an unused variable error. How can I get around it?

case finish := &lt;- termSig:

My current workaround is to Println(finish).

I had tried:-

case _ := &lt;- termSig:

but that doesn't work either.

答案1

得分: 7

只需省略变量和:=

case <-termSig:
英文:

Just omit the variable and the :=:

case &lt;-termSig:

答案2

得分: 2

如在Go Tour中所示,当引入select时,你可以有一个不初始化新变量的情况。

func fibonacci(c, quit chan int) {
    x, y := 0, 1
    for {
        select {
        case c <- x:
            x, y = y, x+y
        case <-quit:  // 看起来正是你的用例
            fmt.Println("quit")
            return
        }
    }
}
英文:

As is shown in the Go Tour when select is introduced, you can have a case that doesn't initialize a new variable.

func fibonacci(c, quit chan int) {
	x, y := 0, 1
	for {
		select {
		case c &lt;- x:
			x, y = y, x+y
		case &lt;-quit:  // looks like exactly your use case
			fmt.Println(&quot;quit&quot;)
			return
		}
	}
}

huangapple
  • 本文由 发表于 2016年1月11日 10:01:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/34713150.html
匿名

发表评论

匿名网友

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

确定