Skip to content

Latest commit

 

History

History
25 lines (19 loc) · 490 Bytes

03.4.1.md

File metadata and controls

25 lines (19 loc) · 490 Bytes

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