在go语言中,给一个空切片增添元素是允许的,但给maps作相同的操作会引起警告:
来看示例,给一个空的maps赋值
package main
func main() {
var m map[string]int
m["one"] = 1 //error
}
panic: assignment to entry in nil map
goroutine 1 [running]:
main.main()
/Users/codoon/hello.go:5 +0x66
goroutine 2 [runnable]:
runtime.forcegchelper()
/usr/local/go/src/runtime/proc.go:90
runtime.goexit()
/usr/local/go/src/runtime/asm_amd64.s:2232 +0x1
goroutine 3 [runnable]:
runtime.bgsweep()
/usr/local/go/src/runtime/mgc0.go:82
runtime.goexit()
/usr/local/go/src/runtime/asm_amd64.s:2232 +0x1
exit status 2
给一空的slice却是ok的:
package main
func main() {
var s []int
s = append(s, 1)
}
窃以为slice与maps的数据结构不一样,slice是可以链式的,要吧动态的扩展,但maps是k:v形式的,k本身需要hash的...留待验证。