Go:分配到nil映射中的条目
当尝试在下面的代码中将值设置为Go:分配到nil映射中的条目,go,runtime-error,goroutine,Go,Runtime Error,Goroutine,当尝试在下面的代码中将值设置为映射(countedData)时,我收到一个错误,该错误表示,分配给nil映射中的条目 func receiveWork(out <-chan Work) map[string][]ChartElement { var countedData map[string][]ChartElement for el := range out { countedData[el.Name] = el.Data } fmt
映射
(countedData
)时,我收到一个错误,该错误表示,分配给nil映射中的条目
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
}
请帮我纠正这个错误
使用内置函数make生成一个新的空映射值,该函数
将映射类型和可选容量提示作为参数:
make(map[string]int)
make(map[string]int, 100)
初始容量并不限制其大小:地图会根据需要进行扩展
除nil映射外,存储在其中的项目数。A.
nil映射相当于空映射,但不能包含任何元素
补充说
你写道:
var countedData map[string][]ChartElement
相反,要初始化映射,请编写
countedData := make(map[string][]ChartElement)
另一个选项是使用复合文字:
countedData := map[string][]ChartElement{}
看起来您的频道进入了
receiveWork
永不关闭。您需要确保它关闭,以便for循环结束。在main函数中,当所有goroutine完成其工作并完成对out通道的写入时,它结束。
countedData := map[string][]ChartElement{}