Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map of channels

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

like image 843
user2486815 Avatar asked Feb 24 '17 16:02

user2486815


People also ask

What is a channel map?

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.

How do I create a Golang map?

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.


1 Answers

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

like image 81
masnun Avatar answered Oct 19 '22 23:10

masnun