在通道变量初始化后创建缓冲通道

Make buffered channel after channel variable initialisation

我可以像这样初始化一个缓冲字符串通道

queue := make(chan string, 10)

但是如何在 Go 中的结构中初始化缓冲通道?基本上我想将内存分配给缓冲的字符串通道。但最初在结构中我只是定义它并在结构初始化中,我想为它分配内存

type message struct {

  queue *chan string
// or will it be 
//queue []chan string

}

func (this *message) init() {

  queue = make(chan string,10)

  this.queue = &queue

}

这样做:

type message struct {
   queue chan string
}

func (m *message) init() {
    m.queue = make(chan string, 10)
}

这种场景不需要取频道地址。

同理:

type message struct {
    queue chan string
}

func (m *message) init() {
    m.queue = make(chan string, 10)
}

但是您似乎对频道是什么感到有点困惑。 *chan string 在 Go 中是一个有效的结构,但通常是不必要的。只需使用普通的 chan string-- 不需要指针。

// or will it be
//queue []chan string

这将是一个频道数组,这也是有效的,但在这种情况下不是您想要的。

通道不是数组。它更像是一个流(就像您在读取文件或网络连接时可能得到的那样)。但也不要把这个比喻做得太过分。