英文:
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 := <- termSig:
My current workaround is to Println(finish)
.
I had tried:-
case _ := <- termSig:
but that doesn't work either.
答案1
得分: 7
只需省略变量和:=
:
case <-termSig:
英文:
Just omit the variable and the :=
:
case <-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 <- x:
x, y = y, x+y
case <-quit: // looks like exactly your use case
fmt.Println("quit")
return
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论