亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Go : 分配到 nil 地圖中的條目

Go : 分配到 nil 地圖中的條目

Go
烙印99 2021-12-13 18:15:38
在下面的代碼中嘗試將值設置為map( countedData) 時,我收到一個錯誤消息,指出assignment to entry in nil map.func receiveWork(out <-chan Work) map[string][]ChartElement {    var countedData map[string][]ChartElement    for el := range out {        countedData[el.Name] = el.Data    }    fmt.Println("This is never executed !!!")    return countedData}Println 不執行(因為在此之前錯誤發生在留置權上)。有一些 goroutines 將數據發送到通道,receiveWork方法應該制作這樣的地圖:map =>    "typeOne" =>        [         ChartElement,         ChartElement,         ChartElement,       ],    "typeTwo" =>        [         ChartElement,         ChartElement,         ChartElement,       ]請幫我修復錯誤。
查看完整描述

2 回答

?
神不在的星期二

TA貢獻1963條經驗 獲得超6個贊

使用內置函數 make 創建一個新的空映射值,該函數將映射類型和可選的容量提示作為參數:

make(map[string]int)
make(map[string]int, 100)

初始容量不限制其大小:地圖增長以容納存儲在其中的項目數量,除了 nil 地圖。一個 nil 映射相當于一個空映射,只是不能添加任何元素。

你寫:

var countedData map[string][]ChartElement

相反,要初始化地圖,請寫入,

countedData := make(map[string][]ChartElement)


查看完整回答
反對 回復 2021-12-13
?
30秒到達戰場

TA貢獻1828條經驗 獲得超6個贊

另一種選擇是使用復合文字:

countedData := map[string][]ChartElement{}

https://golang.org/ref/spec#Composite_literals


查看完整回答
反對 回復 2021-12-13
  • 2 回答
  • 0 關注
  • 186 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號