<分区>
为了说明问题,我写了一些演示代码。请参阅下面的可运行代码:
package main
import (
"fmt"
"time"
)
type structOfChan struct {
Name string
signalCh chan bool
}
func (sc structOfChan) Init() {
sc.signalCh = make(chan bool, 1)
}
func (sc structOfChan) Notify() {
sc.signalCh <- true
fmt.Println(sc.Name, "notified")
}
func main() {
sc1 := structOfChan{
Name: "created with Channel",
signalCh: make(chan bool, 1),
}
sc2 := structOfChan{Name: "created without channel"}
sc2.Init()
go func() {
sc1.Notify()
}()
go func() {
sc2.Notify()
}()
time.Sleep(5 * time.Second)
}
以上代码的输出是创建时通知的 channel
。
这意味着当你创建一个没有 signalCh
的结构,然后通过 init
将其传递给结构时,signalCh
将在某些值传递时阻塞
这是怎么发生的?为什么这两种传递 channel 的方法会有所不同?