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
Channel mapping is a method that goes beyond listing the ways customers are contacted by a company to explore what a company's brand value means to a particular customer.
Go by Example: Maps Maps are Go's built-in associative data type (sometimes called hashes or dicts in other languages). To create an empty map, use the builtin make : make(map[key-type]val-type) . Set key/value pairs using typical name[key] = val syntax. Printing a map with e.g. fmt.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With