英文:
Go : assignment to entry in nil map
问题
在下面的代码中,当尝试给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
语句没有执行(因为错误发生在它之前的一行)。
有一些goroutine正在向通道发送数据,receiveWork
方法应该创建一个如下所示的map:
map =>
"typeOne" =>
[
ChartElement,
ChartElement,
ChartElement,
],
"typeTwo" =>
[
ChartElement,
ChartElement,
ChartElement,
]
请帮我修复这个错误。
英文:
When trying to set value to the map
(countedData
) in the below code, I am getting an error that says, 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
does not execute (as the error occurs on a lien before that).
There are some goroutines , that are sending data to channel, and receiveWork
method should be making a map like this:
map =>
"typeOne" =>
[
ChartElement,
ChartElement,
ChartElement,
],
"typeTwo" =>
[
ChartElement,
ChartElement,
ChartElement,
]
Please help me fix the error.
答案1
得分: 37
《Go编程语言规范》
映射类型
使用内置函数make创建一个新的空映射值,该函数接受映射类型和可选的容量提示作为参数:
make(map[string]int)
make(map[string]int, 100)
初始容量并不限制其大小:映射会根据存储在其中的元素数量进行扩容,除了nil映射。nil映射等同于空映射,但不能添加元素。
你写的代码:
var countedData map[string][]ChartElement
相反,要初始化映射,请写成:
countedData := make(map[string][]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.
You write:
var countedData map[string][]ChartElement
Instead, to initialize the map, write,
countedData := make(map[string][]ChartElement)
答案2
得分: 1
另一种选择是使用复合字面量:
countedData := map[string][]ChartElement{}
https://golang.org/ref/spec#Composite_literals
英文:
Another option is to use a composite literal:
countedData := map[string][]ChartElement{}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论