Gomapmapmapkeykey
1. 字典定义
makemapmap
/* 声明变量,默认 map 是 nil */
var mapName map[mapKey]mapValue

/* 使用 make 函数 */
mapName := make(map[mapKey]mapValue)

这两者区别在:

varmapNamemakemap

定义一个字典类型变量语法格式有以下多种写法:

var mapName  map[mapKey]dataType
var mapName  map[mapKey]dataType = make(map[mapKey]dataType) 
var mapName  = make(map[mapKey]dataType) 
var mapName  map[mapKey]dataType = map[mapKey]dataType{}
var mapName  = map[mapKey]dataType{}
mapName  := map[mapKey]dataType{}
mapName  := make(map[mapKey]dataType)
// 创建一个映射,键的类型是string,值的类型是int
dict := make(map[string]int) // map 容量使用默认值
dict := make(map[string]int, len) // map 容量使用给定的 len 值

// 创建一个映射,键和值的类型都是string
// 使用两个键值对初始化映射
dict := map[string]string{"country": "China", "province": "Shaanxi"}
2. 字典初始化
mapnil mapnil map
nilnil
nil
// 通过声明映射创建一个nil映射
var book map[string]string
book["author"] = "wohu"

Runtime Error:
panic: runtime error: assignment to entry in nil map
makemap
book := make(map[string]string)
book["author"] = "wohu"
fmt.Printf("book is %v\n", book) // book is map[author:wohu]
fmt.Printf("book is %v\n", book["author"]) // book is wohu

或者使用如下赋值

d1 := make(map[string]string)
var d2 = map[string]string{} // 注意:后面带了个大括号
d1["age"] = "18"
d2["name"] = "wohu"
fmt.Printf("d1 is %v\n", d1)	// d1 is map[age:18]
fmt.Printf("d2 is %v\n", d2)	// d2 is map[name:wohu]
len()map
3. 字典键类型约束
Go
Go==!=
Gokey==!=mapnil

s1 := make([]int, 1)
s2 := make([]int, 2)
f1 := func() {}
f2 := func() {}
m1 := make(map[int]string)
m2 := make(map[int]string)
println(s1 == s2) // 错误:invalid operation: s1 == s2 (slice can only be compared to nil)
println(f1 == f2) // 错误:invalid operation: f1 == f2 (func can only be compared to nil)
println(m1 == m2) // 错误:invalid operation: m1 == m2 (map can only be compared to nil)
mapmapkey
panic
4. 遍历字典
map
package main

import "fmt"

func main() {
	book := make(map[string]string)

	book["price"] = "100"
	book["author"] = "wohu"
	book["language"] = "Chinese"

	for k := range book { // 迭代 key, 不能保证每次迭代元素的顺序
		fmt.Println(k, "value is ", book[k])
	}

	for k, v := range book { // 同时迭代 key 和 value
		fmt.Println(k, v)
	}

	/*查看元素在集合中是否存在 */
	published, ok := book["published"] /*如果确定是真实的,则存在,否则不存在 */
	/*fmt.Println(published) */
	/*fmt.Println(ok) */
	if ok {
		fmt.Println("published is ", published)
	} else {
		fmt.Println("published not exist")
	}
}

运行结果为:

price value is  100
author value is  wohu
language value is  Chinese
price 100
author wohu
language Chinese
published not exist
keykeyvalue
// 第一种情况,断言查询,推荐使用这种方法
val,ok := map[key]

// 第二种情况直接查询
val := map[key]

上边两种读取字典的方法中,

oktruekeyokfalsekeykeykeymapvaluevalueintvaluenil
5. 删除 map 元素
Godelete()delete()mapdelete()
delete(map, key)
mapmapkeymap
package main

import "fmt"

func main() {
	book := map[string]string{
		"price":    "100",
		"author":   "wohu",
		"language": "Chinese", // 数组或者字典在多行编写时必须要在最后一个元素后面加逗号
	}
// syntax error: unexpected newline, expecting comma or }
	for k, v := range book {
		fmt.Println("k is ", k, ",v is ", v)
	}

	delete(book, "author")
	for k, v := range book {
		fmt.Println("k is ", k, ",v is ", v)
	}

	mapLength := len(book)
	fmt.Println("book length is ", mapLength)
}
deletemapdeletemapdelete
6. 清空 map
GomapmapmakemapGo
7. 用切片作为 map 的值
keyvaluevaluekey
[]int
mp1 := make(map[int][]int)
mp2 := make(map[int]*[]int)
8. map 的有序遍历

8.1 先对key进行排序,再根据 key 进行遍历

GomapkeyGomapGomapkeykey
package main

import (
	"fmt"
	"sort"
)

func main() {
	//1.定义一个key打乱的字典
	person := map[int]string{3: "张学友", 1: "刘德华", 2: "郭富城", 4: "黎明", 5: "我"}

	//2.定义一个切片
	s := make([]int, 0, len(person))

	//3.遍历map获取key-->s1中
	for key := range person {
		s = append(s, key)
	}

	//4.给s进行排序
	sort.Ints(s)
	// sort.Strings(a)

	//5. 遍历s 来读取 person
	for _, k := range s { // 先下标,再数值
		fmt.Println(k, person[k])
	}
}

输出:

1 刘德华
2 郭富城
3 张学友
4 黎明
5 我

8.2 使用 url.Values{} 进行排序

url.Values{}Gohttp/urlurl.Values
type Values map[string][]string
mapSetAddDelEncode
package main

import (
	"fmt"
	"net/url"
)

func main() {
	v := url.Values{}
	v.Add("1", "一")
	v.Add("2", "二")
	v.Add("3", "三")
	v.Add("4", "四")
	v.Add("5", "五")

	fmt.Printf("%#v", v)
}
9. map 变量的传递开销
mapmapmap
mapmap

package main
  
import "fmt"

func foo(m map[string]int) {
    m["key1"] = 11
    m["key2"] = 12
}

func main() {
    m := map[string]int{
        "key1": 1,
        "key2": 2,
    }

    fmt.Println(m) // map[key1:1 key2:2]  
    foo(m)
    fmt.Println(m) // map[key1:11 key2:12] 
}