英文:
How to populate an array with channels in go
问题
我正在尝试使用Go通道构建一个数组。我不关心插入顺序,但我只从通道中接收到最后一个项目。
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]]
英文:
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
得分: 3
你需要从通道中连续读取数据,因为数据正在被写入其中。当你完成向通道中写入数据时,关闭它。以下是它的工作原理。
注意:AddToMap不作为独立的goroutine调用。可以使用waitgroup来完成,因为我们需要知道何时关闭通道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)
}
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论