英文:
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 "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)
}
答案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 "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 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论