为什么我不能在Go中使用new()初始化地图? [英] Why can't I initialize a map with new() in Go?
问题描述
package main
import "fmt"
func main() {
p := new(map[string]int)
m := make(map[string]int)
m["in m"] = 2
(*p)["in p"] = 1
fmt.Println(m)
fmt.Println(*p)
}
上面的代码给出了错误 panic:分配给nil map中的条目
.如果在将成对插入之前打印 * p
,则输出正确.看来我无法修改 * p
?
The above code gives an error panic: assignment to entry in nil map
. If I print *p
before inserting pairs into it, the output is correct. It seems I just can't modify *p
?
推荐答案
这不是与 new
关键字直接相关的问题.如果未初始化地图,则使用 var
关键字声明地图时,会得到相同的行为,例如:
This is not directly an issue with new
keyword. You would get the same behavior, if you did not initialize your map, when declaring it with var
keyword, for example:
var a map[string]int
a["z"] = 10
解决此问题的方法是初始化地图:
The way to fix this is to initialize the map:
var a map[string]int
a = map[string]int{}
a["z"] = 10
它与 new
关键字的工作方式相同:
And it works the same way, with new
keyword:
p := new(map[string]int)
*p = map[string]int{}
(*p)["in p"] = 1
make(map [string] int)
符合您预期的原因是声明了地图并对其进行了初始化.
The reason make(map[string]int)
does what you expect is that the map is declared and initialized.
这篇关于为什么我不能在Go中使用new()初始化地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!