Maps

1 什么是 map ?

map 是在 Go 中将值(value)与键(key)关联的内置类型。通过相应的键可以获取到值。


 

2 如何创建 map ?

2.1 定义并初始化

通过向 make 函数传入键和值的类型,可以创建 map。make(map[type of key]type of value) 是创建 map 的语法。

personSalary := make(map[string]int)

上面的代码创建了一个名为 personSalary 的 map,其中键是 string 类型,而值是 int 类型。在创建map时已经对其初始化,可以直接添加值。

package main

import "fmt"

func main() {
	personSalary := make(map[string]int)
	personSalary["tom"] = 1000
	fmt.Println(personSalary)
}

上面的程序将输出:map[tom:1000]

注意:用make为map分配内存,容量分配要考虑清楚,上面程序中容量分配为0,往map添加值就会扩容,会创建新的map把之前的map拷贝过去,对性能有消耗。

2.2 只定义不赋值

map 的零值是 nil。如果你想添加元素到 nil map 中,会触发运行时 panic。因此 map 必须使用 make 函数初始化。

package main

import (
    "fmt"
)

func main() {  
    var personSalary map[string]int  //定义一个nil零值的map
    //personSalary["tom"] = 1000  直接添加元素到map 程序崩溃
    if personSalary == nil {
        fmt.Println("map is nil. Going to make one.")
        personSalary = make(map[string]int)  //初始化map
        personSalary["tom"] = 1000
    }
    fmt.Println(personSalary)
}

上面的程序中,personSalary 是 nil,因此需要使用 make 方法初始化,程序将输出 :

map is nil. Going to make one.
map[tom:1000]

2.3 定义并直接初始化

var a map[string]string = map[string]string{key:value}

package main

import "fmt"

func main() {
    var a map[string]string = map[string]string{"name": "egon", "age": "18"}
    fmt.Println(a)
}

上面的代码创建了一个名为 a 的 map,其中键是 string 类型,值也是 string 类型。在创建map时直接赋值。上面程序输出为:map[age:18 name:egon]

 

3 给 map 添加元素

给 map 添加新元素的语法和数组相同。下面的程序给 personSalary map 添加了几个新元素。 key不存在则新增,key存在则重新赋值。

package main

import (
    "fmt"
)

func main() {
    personSalary := make(map[string]int)
    personSalary["steve"] = 12000
    personSalary["jamie"] = 15000
    personSalary["mike"] = 9000
    fmt.Println("personSalary map contents:", personSalary)
}

上面的程序输出:personSalary map contents: map[steve:12000 jamie:15000 mike:9000] 

你也可以在声明的时候赋初值。

package main

import (  
    "fmt"
)

func main() {  
    personSalary := map[string]int {
        "steve": 12000,
        "jamie": 15000,
    }
    personSalary["mike"] = 9000
    fmt.Println("personSalary map contents:", personSalary)
}

上面的程序声明了 personSalary,并在声明的同时添加两个元素。之后又添加了键 mike。程序输出:

personSalary map contents: map[steve:12000 jamie:15000 mike:9000]

键不一定只能是 string 类型。所有可比较的类型,如 boolean,interger,float,complex,string 等,都可以作为键。

 

4 获取 map 中的元素

目前我们已经给 map 添加了几个元素,现在学习下如何获取它们。获取 map 元素的语法是 map[key] 。

package main

import (
    "fmt"
)

func main() {
    personSalary := map[string]int{
        "steve": 12000,
        "jamie": 15000,
    }
    personSalary["mike"] = 9000
    employee := "jamie"
    fmt.Println("Salary of", employee, "is", personSalary[employee])
}

上面的程序很简单。获取并打印员工 jamie 的薪资。程序输出 Salary of jamie is 15000

如果获取一个不存在的元素,会发生什么呢?map 会返回该元素类型的零值。在 personSalary 这个 map 里,如果我们获取一个不存在的元素,会返回 value值的空值,在personSalary这个map里就是int 类型的零值 0

package main

import (  
    "fmt"
)

func main() {
    personSalary := map[string]int{
        "steve": 12000,
        "jamie": 15000,
    }
    personSalary["mike"] = 9000
    employee := "jamie"
    fmt.Println("Salary of", employee, "is", personSalary[employee])
    fmt.Println("Salary of joe is", personSalary["joe"]) //"joe"这个key不存在
}

上面程序输出:

Salary of jamie is 15000
Salary of joe is 0

上面程序返回 joe 的薪资是 0。personSalary 中不包含 joe 的情况下我们不会获取到任何运行时错误。但返回0,到底是joe不存在还是joe对应的value就是0呢?所以,我们需要知道 map 中到底是不是存在这个 key,因此使用下面的语法,判断key是否存在于map。

value, ok := map[key]

上面就是获取 map 中某个 key 是否存在的语法。如果 ok 是 true,表示 key 存在,key 对应的值就是 value ,反之表示 key 不存在。

package main

import (
    "fmt"
)

func main() {
    personSalary := map[string]int{
        "steve": 12000,
        "jamie": 15000,
    }
    personSalary["mike"] = 9000
    newEmp := "joe"
    value, ok := personSalary[newEmp]
    if ok == true {
        fmt.Println("Salary of", newEmp, "is", value)
    } else {
        fmt.Println(fmt.Println(newEmp, "is", value, "not found"))
    }
}

上面的程序中,第 15 行,joe 不存在,所以 ok 是 false。程序将输出:joe is 0 not found

遍历 map 中所有的元素需要用 for range 循环。

package main

import (
    "fmt"
)

func main() {
    personSalary := map[string]int{
        "steve": 12000,
        "jamie": 15000,
    }
    personSalary["mike"] = 9000
    fmt.Println("All items of a map")
    for key, value := range personSalary {
        fmt.Printf("personSalary[%s] = %d\n", key, value)
    }
}

上面程序输出:

All items of a map
personSalary[mike] = 9000
personSalary[steve] = 12000
personSalary[jamie] = 15000

有一点很重要,当使用 for range 遍历 map 时,不保证每次执行程序获取的元素顺序相同,map是无序的。 

 

5 删除 map 中的元素

删除 map 中 key 的语法是 [delete(map, key)]。这个函数没有返回值。

package main

import (  
    "fmt"
)

func main() {  
    personSalary := map[string]int{
        "steve": 12000,
        "jamie": 15000,
    }
    personSalary["mike"] = 9000
    fmt.Println("map before deletion", personSalary)
    delete(personSalary, "steve")
    //delete(personSalary, "tom")  删除的key不存在,程序正常运行,并不会报错
    fmt.Println("map after deletion", personSalary)
}

上述程序删除了键 “steve”,输出:

map before deletion map[steve:12000 jamie:15000 mike:9000]
map after deletion map[mike:9000 jamie:15000]

 

6 获取 map 的长度

获取 map 的长度使用 [len]函数。

package main

import (
    "fmt"
)

func main() {
    personSalary := map[string]int{
        "steve": 12000,
        "jamie": 15000,
    }
    personSalary["mike"] = 9000
    fmt.Println("length is", len(personSalary))
}

上述程序中的 len(personSalary) 函数获取了 map 的长度。程序输出 length is 3

 

7 Map 是引用类型

和 [slices]类似,map 也是引用类型。当 map 被赋值为一个新变量的时候,它们指向同一个内部数据结构。因此,改变其中一个变量,就会影响到另一变量。

package main

import (
    "fmt"
)

func main() {
    personSalary := map[string]int{
        "steve": 12000,
        "jamie": 15000,
    }
    personSalary["mike"] = 9000
    fmt.Println("Original person salary", personSalary)
    newPersonSalary := personSalary
    newPersonSalary["mike"] = 18000
    fmt.Println("Person salary changed", personSalary)

}

上面程序中的第 14 行,personSalary 被赋值给 newPersonSalary。下一行 ,newPersonSalary 中 mike 的薪资变成了 18000 。personSalary 中 Mike 的薪资也会变成 18000。程序输出:

Original person salary map[steve:12000 jamie:15000 mike:9000]
Person salary changed map[steve:12000 jamie:15000 mike:18000]

当 map 作为函数参数传递时也会发生同样的情况。函数中对 map 的任何修改,对于外部的调用都是可见的。

 

8 Map 的相等性

因为map是引用类型,map 之间不能使用 == 操作符判断,== 只能用来检查 map 是否为 nil。如果要判断两个map的值是否相等,可以遍历比较两个 map 中的每个元素。在python中, ==比较的是值,is比较的是内存地址,因此可以用来判断两个引用是否相等。

package main

func main() {
    map1 := map[string]int{
        "one": 1,
        "two": 2,
    }

    map2 := map1

    if map1 == map2 {
    }
}

上面程序抛出编译错误 invalid operation: map1 == map2 (map can only be compared to nil)

 

9 Map 与 切片相互嵌套

Map类型的切片

切片中的元素类型可以是任意类型,因此切片的元素可以放入map类型

package main

import "fmt"

func main() {
    MapSlice := make([]map[string]int, 5) //定义并初始化一个长度为5的 map类型的切片,切片的元素是map类型
    fmt.Println("before map init")
    for index, value := range MapSlice {
        fmt.Printf("slice[%d]=%v\n", index, value)
	}
    //MapSlice[0]["a"] = 100 只初始化了切片,map还没有初始化,不能直接使用,程序崩溃
    fmt.Println()
    MapSlice[0] = make(map[string]int, 10) //对切片0号索引的map进行初始化,然后对这个map添加值
    MapSlice[0]["a"] = 100
    MapSlice[0]["b"] = 200
    MapSlice[0]["c"] = 300
    MapSlice[0]["d"] = 400
    MapSlice[0]["e"] = 500
    fmt.Println("after map init")
    for index, value := range MapSlice {
        fmt.Printf("slice[%d]=%v\n", index, value)
    }
}

 上面的程序输出为:

before map init
slice[0]=map[]
slice[1]=map[]
slice[2]=map[]
slice[3]=map[]
slice[4]=map[]
              
after map init
slice[0]=map[a:100 b:200 c:300 d:400 e:500]
slice[1]=map[]
slice[2]=map[]
slice[3]=map[]
slice[4]=map[]

Map中嵌套切片

map的value可以是任意类型,因此map的vlaue可以放一个切片类型

package main

import "fmt"

func main() {
    SliceMap := make(map[string][]int, 16) //定义并初始化一个容量为16的map,它的key是string,value是切片类型
    //往map中添加key:value, value是切片,需要初始化后才能使用;
    //首先判断key是否存在,如果key不存在,说明对应的value是第一次使用,需要先对切片进行初始化;如果key存在,直接操作切片即可
    key := "student"
    value, ok := SliceMap[key]
    if !ok {
        value = make([]int, 0, 16) //初始化得到一个长度0,容量16的切片
        SliceMap[key] = value      //初始化切片后,可以为map添加key:val
    }
    fmt.Println(SliceMap)
    value = append(value, 100) //给切片追加值
    value = append(value, 200)
    value = append(value, 300)
    SliceMap[key] = value
    fmt.Println(SliceMap)
}

 上面的程序输出为:

map[student:[]]
map[student:[100 200 300]]

 

posted @ 2022-11-17 14:57  不会钓鱼的猫  阅读(188)  评论(0编辑  收藏  举报