阻止通道暢通無阻

預設情況下,通道上的通訊是同步的; 當你傳送一些值時,必須有一個接收器。否則你會得到 fatal error: all goroutines are asleep - deadlock! 如下:

package main

import "fmt"

func main() {
    msg := make(chan string)
    msg <- "Hey There"
    go func() {
        fmt.Println(<-msg)
    }()
}

有一個解決方案使用:使用緩衝通道:

package main

import "fmt"
import "time"

func main() {
    msg :=make(chan string, 1)
    msg <- "Hey There!"
    go func() {
        fmt.Println(<-msg)
    }()
    time.Sleep(time.Second * 1)
}