Go语言map是无序键值对集合,需声明后make初始化;键必须支持==比较(如string、int),不可用切片、map或函数;遍历顺序随机,线程不安全,nil map读写会panic。
Go语言中的map是无序的键值对集合,必须先声明再使用(不能像切片那样直接字面量赋值给未声明变量),且键类型必须支持==比较(如string、int、bool、指针等,但不能是切片、map或函数)。
推荐显式初始化,避免nil map导致运行时panic:
ages := make(map[string]int)
colors := map[string]string{"red": "#ff0000", "blue": "#0000ff"}
var scores map[string]int
scores = make(map[string]int) // 必须make,否则为nil
通过键名访问值,语法简洁,但需注意“不存在的键”会返回零值,不报错:
age := ages["Alice"] → 若"Alice"不存在,age为0(int零值)if age, ok := ages["Bob"]; ok { fmt.Println("Bob is", age) }ok为bool,仅当键存在时为true
ages["Charlie"] = 30(键存在则覆盖,不存在则插入)delete(ages, "Alice")(删除不存在的键无副作用)Go中map遍历顺序是随机的(每次运行可能不同),如需固定顺序,需额外排序键:
for name, age := range ages { fmt.Printf("%s: %d\n", name, age) }
for name := range ages { fmt.Println(name) }
for _, age := range ages { fmt.Println(age) }(用_忽略键)var keys []string
for k := range ages { keys = append(keys, k) }
sort.Strings(keys)
for _, k := range keys { fmt.Printf("%s: %d\n", k, ages[k]) }
使用map时几个关键细节容易出错:
make的map是nil,直接赋值会panic;len(nilMap)返回0,是安全的sync.RWMutex)或使用sync.Map(适用于读多写少场景)type Key struct{ A int; B string }
m := make(map[Key]bool) ✅