Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
25 lines (19 sloc) 488 Bytes

Map值为nil的坑

下面的代码会正常工作:

aMap := map[string]int{}

aMap["test"] = 1

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

aMap := make(string)int{}

aMap = nil

fmt.println(aMap)

aMap["test"] = 1

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

$ go run failMap.go

map[]

panic: assiment to entry in nil map

You can’t perform that action at this time.