Skip to content
Permalink
master
Switch branches/tags
Go to file
 
 
Cannot retrieve contributors at this time

Map值为nil的坑

下面的代码会正常工作:

aMap := map[string]int{}

aMap["test"] = 1

然而下面的代码是不能工作的,因为你将nil赋值给map:

aMap := map[string]int{}

aMap = nil

fmt.Println(aMap)

aMap["test"] = 1

将以上代码保存至failMap.go,执行后会产生下面的错误信息(事实上,如果你用IDE编程,IDE就会提醒你有错误):

$ go run failMap.go

map[]

panic: assignment to entry in nil map