频道地图

huangapple go评论74阅读模式
英文:

Map of channels

问题

我想根据一个字符串索引一些通道。我正在使用一个映射(map),但它不允许我给它分配一个通道。我一直得到"panic: assignment to entry in nil map"的错误,我错过了什么?

package main

import "fmt"

func main() {
    var things map[string](chan int)
    things["stuff"] = make(chan int)
    things["stuff"] <- 2
    mything := <-things["stuff"]
    fmt.Printf("my thing: %d", mything)
}

链接:https://play.golang.org/p/PYvzhs4q4S

英文:

I'd like to index some channels based on a string. I am using a map but it won't allow me to assign a channel to it. I keep getting "panic: assignment to entry in nil map", what am i missing?

package main

import &quot;fmt&quot;

func main() {
	var things map[string](chan int)
	things[&quot;stuff&quot;] = make(chan int)
	things[&quot;stuff&quot;] &lt;- 2
	mything := &lt;-things[&quot;stuff&quot;]
	fmt.Printf(&quot;my thing: %d&quot;, mything)
}

https://play.golang.org/p/PYvzhs4q4S

答案1

得分: 18

你需要先初始化地图。类似这样:

things := make(map[string](chan int))

另外,你正在发送和尝试从一个无缓冲通道中消费数据,所以程序会发生死锁。你可以使用一个带缓冲的通道或者在一个 goroutine 中发送/消费数据。

我在这里使用了一个带缓冲的通道:

package main

import "fmt"

func main() {
    things := make(map[string](chan int))
    
    things["stuff"] = make(chan int, 2)
    things["stuff"] <- 2
    mything := <-things["stuff"]
    fmt.Printf("my thing: %d", mything)
}

Playground链接:https://play.golang.org/p/DV_taMtse5

make(chan int, 2) 部分将通道设置为带有长度为 2 的缓冲区。在这里可以了解更多信息:https://tour.golang.org/concurrency/3

英文:

You need to initialize the map first. Something like:

things := make(map[string](chan int))

Another thing, you're sending and trying to consume from an unbuffered channel, so the program will be deadlocked. So may be use a buffered channel or send/consume in a goroutine.

I used a buffered channel here:

package main

import &quot;fmt&quot;

func main() {
	things := make(map[string](chan int))
	
	things[&quot;stuff&quot;] = make(chan int, 2)
	things[&quot;stuff&quot;] &lt;- 2
	mything := &lt;-things[&quot;stuff&quot;]
	fmt.Printf(&quot;my thing: %d&quot;, mything)
}

Playground link: https://play.golang.org/p/DV_taMtse5

The make(chan int, 2) part makes the channel buffered with a buffer length of 2. Read more about it here: https://tour.golang.org/concurrency/3

huangapple
  • 本文由 发表于 2017年2月25日 00:15:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/42443370.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定