【问题标题】:Make buffered channel after channel variable initialisation在通道变量初始化后建立缓冲通道
【发布时间】:2017-08-10 03:28:00
【问题描述】:

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

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

}

【问题讨论】:

  • 不要打电话给你的接收者this。给它一个有意义的名字。类型的第一个字母很常见,所以m 在你的情况下。

标签: go memory-management channel


【解决方案1】:

这样做:

type message struct {
   queue chan string
}

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

在这种情况下不需要获取通道的地址。

【讨论】:

    【解决方案2】:

    同理:

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

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

    // 还是会
    //队列[]chan字符串

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

    通道不是数组。它更像是一个流(当您读取文件或网络连接时可能会得到)。但也不要把这个类比走得太远。

    【讨论】:

      猜你喜欢
      • 2014-01-30
      • 2019-01-07
      • 2023-03-30
      • 2021-10-13
      • 2016-08-30
      • 1970-01-01
      • 1970-01-01
      • 2016-06-20
      • 1970-01-01
      相关资源
      最近更新 更多