【发布时间】:2020-05-24 09:32:20
【问题描述】:
我是 golang 的新手。我正在尝试了解频道的工作原理,但这确实令人困惑。
我评论了我的问题。有人可以向我解释为什么这段代码会以这种奇怪的方式表现吗?
package main
import "fmt"
func main() {
slice := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}
c := make(chan int)
go pokeVals(slice, c)
fmt.Println(slice)
fmt.Println("start")
<-c // why 2 "poke"s here?
fmt.Println("-")
<-c // why 0 "poke"s?
//<-c // But if uncommented - 2 more "pokes" here
fmt.Println("end")
}
func pokeVals(values []int, c chan int) {
for _, val := range values {
fmt.Println("poke")
c <- val
}
fmt.Println("overpoked")
}
Golang 操场链接:https://play.golang.org/p/u__cVyUbNJY
【问题讨论】: