Skip to content

Latest commit

 

History

History
25 lines (20 loc) · 612 Bytes

File metadata and controls

25 lines (20 loc) · 612 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: assiment to entry in nil map

这意味着试图向nil map中插入值是不行的,但是查找、删除、长度以及使用range循环是可以的。