Golang通过range遍历channel内容
1、通过range遍历channel内容
package main import ( "fmt" ) func main() { ch := make(chan int) //创建一个无缓存channel //新建一个goroutine go func() { for i := 0; i < 5; i++ { ch <- i //往通道写数据 } //不需要再写数据时,关闭channel close(ch) //ch <- 6 //关闭channel后无法再发送数据 }() for num := range ch { fmt.Println("num = ", num) } }
执行结果:
num = 0 num = 1 num = 2 num = 3 num = 4