go - 如何在 go 中使用 channel 填充数组

标签 go channels

我正在尝试构建一个带有 go channel 的数组。我不关心广告订单,但我只收到来自 channel 的最后一项。

package main

import (
    "fmt"
)

func AddToMap(thing string, val string, c chan map[string]string) {
    mappy := make(map[string]string)
    mappy[thing] = val
    c <- mappy
}

func main() {
    item := make([]map[string]string, 0, 10)
    list1 := []string{"foo", "bar", "baz", "blah", "barf"}
    list2 := []string{"one", "two", "three", "four", "five"}
    c := make(chan map[string]string)
    for index, val := range list1 {
    go AddToMap(val, list2[index], c)
}
    ret := <-c
    item = append(item, ret)
    fmt.Println(item)
}

我的输出是:[map[barf:five]]

最佳答案

当数据被写入其中时,您需要从 channel 中连续读取。当你完成将数据泵入 channel 后,关闭它。这是它的工作原理。

注意:AddToMap 没有作为独立的 goroutine 被调用。这可以使用 waitgroup 来完成,因为我们需要知道何时需要关闭 channel c,这将在所有 AddToMap 运行之后。

package main

import (
    "fmt"
)

func AddToMap(thing string, val string, c chan map[string]string) {
    mappy := make(map[string]string)
    mappy[thing] = val
    c <- mappy
}

func main() {
    item := make([]map[string]string, 0, 10)
    list1 := []string{"foo", "bar", "baz", "blah", "barf"}
    list2 := []string{"one", "two", "three", "four", "five"}
    c := make(chan map[string]string)
    go func(){
        for index, val := range list1 {
            AddToMap(val, list2[index], c)
        }
        close(c)
    }()
    for ret := range c {
        item = append(item, ret)
    }
    fmt.Println(item)
}

关于go - 如何在 go 中使用 channel 填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36563396/

相关文章:

python - Django channel 不会使用 CHANNEL_LAYERS 启动 redis 服务器

去教程: Channels and Buffered Channels

javascript - 如何使用 eventChannel 将函数传递给 redux-saga 中的回调

go - 试图在 golang 中获取具有截止日期的锁?

mysql - (go-sql-driver/mysql) packets.go 中意外的 EOF 和繁忙缓冲区

go - 在 Golang 中传递 interface{} 或 []interface{}

python - 值错误 : number of input channels does not match corresponding dimension of filter, 512 != 3

android - Gomobile android 使用回调

go - 正确等待全局变量初始化

python - 分别读取不同的流