如何确保由通道和映射组成的结构通过引用传递?

How to ensure that a Struct that is made up of channels and map gets passed by reference?

我有以下结构,其中包含通道和用于存储数据的映射。我希望能够将该结构传递给函数,以便使用这些通道,以便一旦它们是 triggered/have 传入消息,就可以使用它们来更新与其关联的地图。

我知道地图在发送到各种函数时默认是通过引用传递的。即使它们包含在自定义结构中,情况是否相同?我如何确保我的整个结构通过引用传递给函数以更新存储并利用其通道?

type CustomStrct struct {
Storage      map[string]string
RetrieveChannel    chan string
InsertChannel      chan string
}

这是我为初始化结构的新实例而创建的构造函数:

func InitializeNewStore() CustomStrct {
    newCustomStruct := CustomStrct {
        Storage:      make(map[string]string),
        RetrieveChannel:    make(chan Request),
        InsertChannel:    make(chan Request),
       }
 
return newCustomStruct 
}

切片、映射和通道在 Go 中是 pointer-like 值:复制包含通道的结构会复制对通道的引用,而不是通道本身:

a := CustomStrct{
    RetrieveChannel: make(chan Request),
}
b := a
log.Println(a.RetrieveChannel == b.RetrieveChannel)    // logs true

所以通过值或引用传递你的结构是很好的。

如果您需要确保 go vet 会标记按值传递结构的尝试,最简单的解决方案是在结构中嵌入 sync.Mutex

type CustomStrct struct {
    mu sync.Mutex
    ...
}

您不需要实际使用互斥锁:只要将它嵌入到结构中就会导致 go vet 在您尝试按值传递它时报错。