gpt4 book ai didi

转到 : assignment to entry in nil map

转载 作者:IT王子 更新时间:2023-10-29 00:48:29 35 4
gpt4 key购买 nike

当尝试在下面的代码中为 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 正在向 channel 发送数据,receiveWork 方法应该制作这样的 map :

map =>
"typeOne" =>
[
ChartElement,
ChartElement,
ChartElement,
],
"typeTwo" =>
[
ChartElement,
ChartElement,
ChartElement,
]

请帮我修正错误。

最佳答案

The Go Programming Language Specification

Map types

A new, empty map value is made using the built-in function make, which takes the map type and an optional capacity hint as arguments:

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

The initial capacity does not bound its size: maps grow to accommodate the number of items stored in them, with the exception of nil maps. A nil map is equivalent to an empty map except that no elements may be added.

你写:

var countedData map[string][]ChartElement

相反,要初始化 map ,请编写,

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

关于转到 : assignment to entry in nil map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35379378/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com