Golang。 渠道图

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

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

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