我是 Go 語言的新手,目前正在參加 Go 之旅。我對語句中的并發(fā)示例 5有疑問。select下面的代碼已使用打印語句進(jìn)行編輯,以跟蹤語句的執(zhí)行。package mainimport "fmt"func fibonacci(c, quit chan int) { x, y := 0, 1 fmt.Printf("Run fib with c: %v, quit: %v\n", c, quit) for { select { case c <- x: fmt.Println("Run case: c<-x") x, y = y, x+y fmt.Printf("x: %v, y: %v\n", x, y) case <-quit: fmt.Println("Run case: quit") fmt.Println("quit") return } }}func runForLoop(c, quit chan int) { fmt.Println("Run runForLoop()") for i := 0; i < 10; i++ { fmt.Printf("For loop with i: %v\n", i) fmt.Printf("Returned from c: %v\n", <-c) } quit <- 0}func main() { c := make(chan int) quit := make(chan int) go runForLoop(c, quit) fibonacci(c, quit)}以下內(nèi)容打印到控制臺。Run fib with c: 0xc00005e060, quit: 0xc00005e0c0Run runForLoop()For loop with i: 0Returned from c: 0 // question 1For loop with i: 1Run case: c<-x // question 2x: 1, y: 1Run case: c<-x // question 2x: 1, y: 2Returned from c: 1For loop with i: 2Returned from c: 1For loop with i: 3// ...我的問題是即使沒有執(zhí)行任何選擇塊,也會c在此處收到的值。0我可以確認(rèn)這是具有類型的c變量的零值嗎?int為什么要c<-x執(zhí)行兩次?
Go Tour #5:選擇語句示例
ibeautiful
2022-06-13 17:09:35