go map 操作

创建一个空的map:

var m map[int]string
m = map[int]string{}
fmt.Println(m)

使用 make 关键字:

var m map[int]string
m = make(map[int]string)
fmt.Println(m)

简写:

var m map[int]string = make(map[int]string)
// m := make(map[int]string)
fmt.Println(m)

存取:

m := make(map[int]string)
m[1] = "ok"
m[2] = "ok"
fmt.Println(m)
delete(m, 2)
fmt.Println(m)

复杂map:

m := make(map[int]map[int]string)
m[1] = make(map[int]string)
m[1][1] = "ok"
fmt.Println(m)

利用多返回值处理未初始化的情况:

m := make(map[int]map[int]string)
a, ok := m[1][1]
if !ok {
	m[1] = make(map[int]string)
}
m[1][1] = "GOOD"
a, ok = m[1][1]
fmt.Println(m, a)

数组嵌套 map 初始化(错误方法):

sm := make([]map[int]string, 5)
for _, v := range sm {
	//这里v是map中值的一个拷贝,修改v不会影响原值
	v = make(map[int]string, 1)
	v[1] = "ok"
	fmt.Println(v)
}
fmt.Println(sm)

数组嵌套 map 初始化:

sm := make([]map[int]string, 5)
for i := range sm {
	sm[i] = make(map[int]string, 1)
	sm[i][1] = "ok"
	fmt.Println(sm[i])
}
fmt.Println(sm)

完成 map 中 key 的排序:

m := map[int]string{1: "a", 2: "b", 3: "c"}
s := make([]int, len(m))
i := 0
for k, _ := range m {
	s[i] = k
	i++
}
sort.Ints(s)
fmt.Println(s)
输出:
	[1 2 3]

完成 map 中 key/value 的交换:

package main

import (
	"fmt"
)

func main() {
	m1 := map[int]string{1: "a", 2: "b", 3: "c", 4: "d", 5: "e"}
	fmt.Println(m1)
	m2 := make(map[string]int)

	for k, v := range m1 {
		m2[v] = k
	}
	fmt.Println(m2)
}