如何使用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]]

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