在Go语言的select语句中,如何评估一个case呢?

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

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 &lt;- x:
		x, y = y, x+y

	case &lt;-quit:
		return
	}
  }
}

My question is :

what is case c &lt;-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 &lt; 10; i++ {
		fmt.Println(&lt;-c)
	}
	quit &lt;- 0
  }()
 fibonacci(c, quit)
}

答案1

得分: 1

case c <- x: 只有在通道 c 可以接收数据时才会成功。它成功发送了 x 的值,然后通过 x, y = y, x+y 这一行将 x 的值更改为 y 的先前值,并生成了斐波那契数列。

通过这种方式,如果没有接收者接收通道 c 的数据,循环不会被阻塞,因为循环会一直进行,直到退出通道接收到一个值。

在主函数中,goroutine 内部的通道接收来自 select 语句发送的消息,并释放通道以接收新的消息。

请参考这个示例以获得更多理解。

英文:

That case c &lt;- 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.

huangapple
  • 本文由 发表于 2021年9月12日 01:02:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/69145081.html
匿名

发表评论

匿名网友

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

确定