```go
package main
import (
"fmt"
)
func main() {
chInt := make(chan int, 100)
for i := 0; i < 10; i++ {
chInt <- i
}
close(chInt)
chFlag := make(chan bool, 1)
defer close(chFlag)
go func() {
for {
select {
case v := <-chInt:
fmt.Println(v)
default:
chFlag <- true
return
}
}
}()
<-chFlag
}```
上面close(chInt) 为啥会导致select 一直在 case v := <-chInt:
fmt.Println(v) 死循环输出0 ,
删掉close(chInt) 或改成defer close(chInt) 就运行正常,符合预期
更多评论
https://tour.golang.org/concurrency/4
这里可以看到其实从chan里取数据可以取第二个参数,chan是否已经close而且没有需要读的值
https://tour.golang.org/concurrency/5
这里可以看到在select里,close chan一般的用途……
就标准文档的话,看语言特性表:
https://golang.org/ref/spec#Receive_operator
A receive operation on a closed channel can always proceed immediately, yielding the element type's zero value after any previously sent values have been received.
#3