英文:
how is a case evaluated in Go select statemnet
问题
这里是《Go之旅》中展示了在Go语言中使用select
语句的代码。
func fibonacci(c, quit chan int) {
x, y := 0, 1
for {
select {
case c <- x:
x, y = y, x+y
case <-quit:
return
}
}
}
我的问题是:
这里的case c <- x
是做什么用的?是将一些数据x
发送到通道中,还是在寻找发送数据到通道的条件?
如果将数据发送到循环中,循环应该永远不会结束,但是如果评估发送到通道的数据的条件,我看不到任何数据被发送到通道中。
main
函数如下:
func main() {
c := make(chan int)
quit := make(chan int)
go func() {
for i := 0; i < 10; i++ {
fmt.Println(<-c)
}
quit <- 0
}()
fibonacci(c, quit)
}
英文:
Here is the code from A tour of Go
to demonstrate the use of select
statements in Go.
func fibonacci(c, quit chan int) {
x, y := 0, 1
for {
select {
case c <- x:
x, y = y, x+y
case <-quit:
return
}
}
}
My question is :
what is case c <-x
doing here? is some data x
being sent to the channel or we are looking for the condition when some data is being sent to the channel.
If some data is being sent to the loop, the loop should never end and if the condition of a data sent to channel is evaluated I cannot see any data being sent to the channel.
The main
function is:
func main() {
c := make(chan int)
quit := make(chan int)
go func() {
for i := 0; i < 10; i++ {
fmt.Println(<-c)
}
quit <- 0
}()
fibonacci(c, quit)
}
答案1
得分: 1
case c <- x:
只有在通道 c
可以接收数据时才会成功。它成功发送了 x
的值,然后通过 x, y = y, x+y
这一行将 x
的值更改为 y
的先前值,并生成了斐波那契数列。
通过这种方式,如果没有接收者接收通道 c
的数据,循环不会被阻塞,因为循环会一直进行,直到退出通道接收到一个值。
在主函数中,goroutine 内部的通道接收来自 select 语句发送的消息,并释放通道以接收新的消息。
请参考这个示例以获得更多理解。
英文:
That case c <- x:
will be successful if channel c
is free to receive data only. And it successfully send that value of x
, then x
's value is changed to y
's previous value with line x, y = y, x+y
and populate fibonacci.
In this way, If there is no receiver to the channel c
, there is no blocking because the loop always continuing and quit when the quit channel receives a value.
In the main function, inside the goroutine channel receives messages sent from the select case and free up the channel for a new message.
Please refer to this example for more understanding.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论