结构中的Golang通道在创建结构时会通过传递行为,而在创建[duplicate]之后通过函数传递行为会有所不同

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?

</div>

https://play.golang.org/p/TIn7esSsRUZ

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)

}

output:

created with Channel notified created without channel notified

To be able to modify struct fields, you need to make reciever functions on pointer values