go_study/bilibili/aceld/goroutine/channel/test3/main.go

28 lines
421 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import "fmt"
func main() {
c := make(chan int)
go func() {
for i := 0; i < 5; i++ {
c <- i
}
// close可以关闭一个channel
close(c)
}()
for {
// 如果ok为true表示channel没有关闭如果ok为false表示channel已经关闭
if data, ok := <-c; ok {
fmt.Println(data)
} else {
fmt.Println("channel c 已被关闭")
break
}
}
fmt.Println("Main finished ...")
}