结构中的Golang通道在创建结构时通过传递它,而在创建后通过函数传递则表现不同

时间:2019-05-20 09:19:53

标签: go struct channel

为说明问题,我编写了一些演示代码。请参见下面的可运行代码:

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)

}

以上代码的输出为created with Channel notified

这意味着当您创建不包含signalCh的结构,然后通过init将其传递给该结构时,signalCh将在传递某些值时阻塞。

这是怎么发生的?为什么两种通过通道的方法会有所不同?

1 个答案:

答案 0 :(得分:0)

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)

}

输出:

created with Channel notified created without channel notified

要能够修改结构字段,您需要在指针值上创建接收函数