示例代碼:
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.")
}