若是不判斷chan是否關閉spa
Notice: 如下代碼會產生死循環code
代碼以下:blog
package main import ( "fmt" ) func main() { c := make(chan int, 10) c <- 1 c <- 2 c <- 3 close(c) for { fmt.Println(<-c) } }
判斷短chan是否關閉
it
package main import ( "fmt" ) func main() { c := make(chan int, 10) c <- 1 c <- 2 c <- 3 close(c) for { i, isClose := <-c if !isClose { fmt.Println("channel closed!") break } fmt.Println(i) } }