To illustrate the problem, I wrote some demo codes. See the runnable code below:
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)
}
The output of above code is created with Channel notified
.
That means when you create a struct without signalCh
and then pass it to the struct by init
, signalCh
will block when some value passed to it.
How did this happen? why does the two approach of passing channels make the difference?