packagemainfuncmain() {var ch chanbool ch <-true// deadlocks because ch is nil}---------Output-----------fatal error: all goroutines are asleep - deadlock!
通道没有初始化值则为nil,所以上述程序会永久阻塞(发生死锁)。
上述代码并无利用价值,它属于缺陷(Bug)。请不要这样做!
从nil通道接收数据会永久阻塞
package main
import "fmt"
func main() {
var ch chan bool
fmt.Printf("Value received from ch is: %v\n", <-ch) // deadlock because ch is nil
}
--------Output---------
fatal error: all goroutines are asleep - deadlock!
类似的,这也会引发死锁,是Bug,请不要这样做!
向已关闭通道发送会引发恐慌
package main
import (
"fmt"
"time"
)
func main() {
var ch = make(chan int, 100)
go func() {
ch <- 1
time.Sleep(time.Second)
close(ch)
ch <- 1
}()
for i := range ch {
fmt.Printf("i: %d\n", i)
}
}