golang中map是引用类型,应用类型的变量未初始化时默认的zero value是nil。直接向nil map写入键值数据会导致运行时错误
panic: assignment to entry in nil map
因为在声明alphabetMap后并未初始化它,所以它的值是nil, 不指向任何内存地址。需要通过make方法分配确定的内存地址。程序修改后即可正常运行:
package main
import "fmt"
const alphabetStr string = "abcdefghijklmnopqrstuvwxyz"
func main() {
alphabetMap := make(map[string]bool)
for _, r := range alphabetStr {
c := string(r)
alphabetMap[c] = true
}
fmt.Println(alphabetMap["x"])
alphabetMap["x"] = false
fmt.Println(alphabetMap["x"])
}