17.Map类型
Map 是一种无序的键值对的集合。Map 最重要的一点是通过 key 来快速检索数据,key 类似于索引,指向数据的值。
Map 是一种集合,所以我们可以像迭代数组和切片那样迭代它。不过,Map 是无序的,我们无法决定它的返回顺序,这是因为 Map 是使用 hash 表来实现的。
//map是一个引用类型,必须初始化才能使用,否则会panic
// var a map[key类型]value类型
1: var a map[string]int
2: var b map[int]string
3: var c map[float32]string
1: func main() {2: var a map[string]int
3: if a == nil {
4: a = make(map[string]int, 16)
5: fmt.Printf("a=%v ", a)
6: a['stu01'] = 10007: fmt.Printf("a=%v ", a)
8: }9: }
如果不初始化 map,那么就会创建一个 nil map。nil map 不能用来存放键值对.也可以声明时就初始化
1: func main() {2: a := map[string]int {
3: "steve":12000,
4: "jamie":15000,
5: }6: a["mike"] = 9000
7: }
基本操作
1: b:="jamie"
2: fmt.Println("Salary of", b, "is", a[b])
1: >>> Salary of jamie is 15000
判定map指定的key是否存在,固定语法
1: value, ok:=map[key]2: c:="steve"
3: value, ok:=a[b]4: if ok == true {
5: fmt.Println("Salary of" b "is" value)6: }else {
7: fmt.Println("key b does not exist")
8: }
map删除元素
1: delete(a, "steve")
2: 全部删除3: for key, _ := range a {4: delete(a, key)5: }
map拷贝
1: b := a
// map属于引用类型,里面存储的都是地址,将a赋值给b,两者指定的是同一map,修改b同时也会修改a
map进行排序:虽然默认是无序的,如果有需要,可以按照有序来进行遍历
1: func main() {2: var a map[string]int = make(map[string]int, 10)3: for i :=0; i<10; i++ {4: key := fmt.Sprintf("key%d", i)
5: a[key] = i6: }7: var keys []string
8: for key, _ := range a {9: keys = append(keys, key)10: }11: sort.Strings(keys)12: for _, key := range keys {13: fmt.Printf("%s=%d ", key, a[key])
14: }15: }
1: >>> key0=02: key1=13: key2=24: ...
map类型的切片
一个稍微复杂的嵌套例子
1: func main() {2: var mapSlice []map[string]int
3: mapSlice = make([]map[string]int, 5)
4: fmt.Println("before map init")
5: for index,value := range mapSlice {
6: fmt.Printf("index:%d value:%v ", index, value)7: }8: mapSlice[0] = make(map[string]int, 10)
9: mapSlice[0]["a"] = 1000
10: mapSlice[0]["b"] = 2000
11: mapSlice[0]["c"] = 3000
12: mapSlice[0]["d"] = 4000
13: fmt.Println("after map init")
14: for index, value := range mapSlice {
15: fmt.Printf("index:%d value:%v ", index, value)16: }17: }
1: >>> before map init2: index:0 value:map[]
3: index:1 value:map[]
4: index:2 value:map[]
5: index:3 value:map[]
6: index:4 value:map[]
7: after map init8: index:0 value:map[a:1000 b:2000 c:3000 d:4000]
9: index:1 value:map[]
10: index:2 value:map[]
11: index:3 value:map[]
12: index:4 value:map[]
练习
1.统计一个字符串每个单词出现的次数。比如:s = "how do you do"输出how = 1 do = 2 you = 1
1: package main2: import (
3: "fmt"
4: "strings"
5: )6: var s = "how do you do what are you doing"
7: func statWords (str string) map[string]int {8: var result map[string]int = make(map[string]int, 128)9: words := strings.Split(str, " ")
10: for _, v := range words {11: count, ok := result[v]
12: if !ok {
13: result[v] = 114: } else {
15: result[v] = count + 1
16: }17: }18: return result
19: }20: func main() {21: result := statWords(s)22: fmt.Println(result)23: }
1: >>> map[do:2 doing:1 you:2 how:1 what:1 are:1]
2.实现学生信息的存储,学生有id,年龄,分数等信息。需要非常方便的通过id查找到对应学生的信息。
1: func stu_info () {2: var stuMap map[int]map[string]interface{}
3: //id=1 name=stu01 score=78.2 age=18
4: stuMap = make(map[int]map[string]interface{}, 16)
5: var id = 16: var name = "stu01"7: var score = 78.28: var age = 189: value, ok := stuMap[id]10: if !ok {
11: value = make(map[string]interface{}, 8)
12: value["name"] = name13: value["id"] = id
14: value["score"] = score
15: value["age"] = age
16: stuMap[id] = value17: } else {
18: value["name"] = name19: value["id"] = id
20: value["score"] = score
21: value["age"] = age
22: }23: stuMap[id] = value24: fmt.Println(stuMap[1])25: }26: func main () {27: stu_info()28: }
1: >>> map[score:78.2 age:18 name:stu01 id:1]