dongshao2967 2016-04-12 03:59
浏览 182

如何使用Go中的通道填充数组

I am trying to build an array with go channels. I do not care about insertion order however I only receive the last item from the 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)
}

My output is: [map[barf:five]]

  • 写回答

1条回答 默认 最新

  • donglizhan7848 2016-04-12 04:38
    关注

    You need to read continuously from channel, as data is being written into it. And when you're done pumping data into channel, close it. Here is how it can work.

    Note: AddToMap is not being called as independent goroutine. It can be done using waitgroup, because we need to know when we need to close channel c, which will be after all AddToMap have been run.

    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)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的代码运行
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败