2017-02-24 82 views
0

我想根據字符串爲某些頻道編制索引。我正在使用地圖,但不允許我爲其分配頻道。我不斷收到「恐慌:分配到無地圖入口」,我錯過了什麼?Golang。頻道地圖

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

+4

你用'make'或者地圖文字初始化地圖。也許要經過[「Go of Go」](https://tour.golang.org/),它涵蓋了所有的基礎知識。 – JimB

+0

只是一個小小的說明,以防萬一:地圖的零值爲零。正如答案所述,你需要用'make'來初始化它# – threeve

回答

5

您需要首先初始化地圖。例如:

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

遊樂場鏈路:https://play.golang.org/p/DV_taMtse5

make(chan int, 2)部與爲2的緩衝長度中緩衝的信道瞭解更多關於在這裏:​​https://tour.golang.org/concurrency/3

+0

出於好奇,爲什麼你把'chan int'放在括號裏?語法'make(map [string] chan int)'工作正常。 –

+0

即使像'map [string] chan int {}'也行得通。 –

+1

哦,它是在原來的代碼。我修改了我必須修改的部分。 – masnun