示例代码:
package main
import (
"fmt"
"time"
)
func hello(channel_hello chan string) {
fmt.Println("hello.")
//确保hello打印输出
time.Sleep(1*time.Second)
//发送数据到通道
channel_hello <- "hello_channel"
//关闭通道,通知接受者此通道不会再发送数据
close(channel_hello)
}
func main() {
//创建无缓冲通道channel,用于goroutine之间通信
channel_hello := make(chan string)
//创建协程goroutine
go hello(channel_hello)
status_flag := true
for status_flag {
select {
case chan_receive,chan_status := <- channel_hello:
if chan_status {
//从通道接收数据
fmt.Println("msg receive from channel success:", chan_receive)
} else {
//通道被关闭
status_flag = false
fmt.Println("chan close success", chan_status)
}
default:
}
}
fmt.Println("main end.")
}