【问题标题】:How to pass array of channels如何传递通道数组
【发布时间】:2019-04-23 07:42:47
【问题描述】:

我正在尝试将一组通道传递给方法“func Data(channel chan

     func Data(channel chan<- []Book) {
            var data EData
            data = ReadJSONFile("Data.json")

            go Writer(data.BookStores[0].Central, channel[0]) // at this 
          // place I get "invalid operation:  channel[0] (type chan<- []Book 
          // does not support indexing)"
        }

【问题讨论】:

标签: go


【解决方案1】:

chan&lt;- []Book 需要变为 []chan&lt;- Book[] 在 go 中修改了它后面的类型,所以如果你想要一个通道数组,把它放在 chan 之前。

func Data(channel []chan<- Book) {
    var data EData
    data = ReadJSONFile("Data.json")

    go Writer(data.BookStores[0].Central, channel[0])
    // ...
}

测试:https://play.golang.org/p/sQt3VawvhoI

【讨论】:

    【解决方案2】:

    传递 Book 元素通道切片的正确类型是:

    []chan<- Book
    

    您原始问题中的代码是用于图书切片的频道。

    【讨论】:

      猜你喜欢
      • 2018-04-02
      • 2016-04-11
      • 1970-01-01
      • 2021-08-22
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 2021-01-14
      • 1970-01-01
      相关资源
      最近更新 更多