struct 中的 Golang channel 表现不同,在创建 struct 时传递它,在创建后通过函数传递

标签 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)

}

以上代码的输出是创建时通知的 channel

这意味着当你创建一个没有 signalCh 的结构,然后通过 init 将其传递给结构时,signalCh 将在某些值传递时阻塞

这是怎么发生的?为什么这两种传递 channel 的方法会有所不同?

最佳答案

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)

}

输出:

创建时通知 channel 在未通知 channel 的情况下创建

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

关于struct 中的 Golang channel 表现不同,在创建 struct 时传递它,在创建后通过函数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56217825/

相关文章:

post - 使用带有 map 数据的结构

multithreading - 我怎样才能拥有两个具有相同功能的 goroutine 来查看彼此的值?

java - 使用 channel 将数据从 outputStream 传递到 bytebuffer

go - 有没有办法确定当前步骤是否是目录?

golang tabwriter 格式不正确

multithreading - 如何在go中实现简单的流量整形

带有结构体和二维数组的 C 指针

iis - 在 IIS 上运行 go web 应用程序

c++ - 退出后代码崩溃?

go - go 中奇怪的 channel 行为