我正在浏览tour的示例.golang .org,我遇到了这个我不太理解的代码:
package main
import "fmt"
func fibonacci(c, quit chan int) {
x, y := 0, 1
for {
select {
case c <- x: // case :将x发送到通道c?
x, y = y, x+y
case <-quit: // case: receive from channel quit?
fmt.Println("quit")
return
}
}
}
func main() {
c := make(chan int)
quit := make(chan int)
go func() { // when does this get called?
for i := 0; i < 10; i++ {
fmt.Println(<-c)
}
quit <- 0
}()
fibonacci(c, quit)
}
我理解通道如何工作的基础知识,但我不理解的是上面的SELECT语句是如何工作的.教程上的说明是这样说的:
"The select statement lets a goroutine wait on multiple communication operations. A select blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready."个
但这些案件是如何执行的?据我所知,他们在说:
case :将x发送到通道c
case :从退出接收
我想我理解了第二个函数只有在Quit有一个值的情况下才会执行,这个值稍后在go函数()中完成.但是第一个判断的 case 是什么呢?另外,在go func()中,我们显然是打印c中的值,但是c在这一点上不应该有任何内容?我能想到的唯一解释是go func()在调用Fibonacci()之后以某种方式执行.我猜这是一只猩猩,我也不完全理解,它看起来就像是魔术.
如果有人能通读这段代码并告诉我它在做什么,我将不胜感激.