Skip to main content

Go: map 映射

📅 2026-02-06 ✏️ 2026-03-06 Inside Go CS GO
go version # go version go1.25.6

1 · map 映射#

A map is an unordered group of elements of one type, called the element type, indexed by a set of unique keys of another type, called the key type.

映射是一组无序的对应某种类型的元素,通过另一种类型的唯一值索引。

MapType = “map” ”[” KeyType ”]” ElementType .

KeyType 类型必须是可比较的:映射map,切片slice,函数function都不能作为KeyType

可比较的类型有:布尔值、数字、字符串、指针、chan管道?、interface接口?,结构体、数组

1.1 · 初始化

  1. 字面量
  2. make
// 1. literal:
map1 := map[string]string{
    "key1": "val1",
    "key2": "val2",
}
// 2. make: make([]T, length, capacity)
map2 := make(map[string]string, 2) // 第二个参数为hint,与具体大小无关,仅为性能优化提示

// NOTE: 未初始化的map是nil值
// 读取nil的map获取元素类型零值,往nil的map里面写值会panic
var map3 map[string]string
print(map3 == nil) // true

1.2 · 相关操作

// len 获取长度
map1 := make(map[string]string)
maplent := len(map1)
// 赋值语句
map1["key1"] = "val1"
// 索引表达式
val1     := map1["key1"]
val1, ok := map1["key1"]
// delete/clear 删除元素
delete(map1, "key1")
clear(map1)

1.3 · maps 包(依赖范型)#

https://pkg.go.dev/maps@go1.25.6

go doc maps
  1. 创建、构造
  2. 遍历、迭代
  3. 比较
  4. 修改:增、删、复制(覆盖)

NOTE: 带Func后缀,提供自定义比较/过滤的泛化版本

NOTE: 与迭代器之间的交互

1.4 · Inside Map#

1.4.1 · swiss map#

https://go.dev/blog/swisstable

1.4.2 · no swiss map#

  1. https://go.dev/ref/spec#Map_types
  2. https://go.dev/blog/maps