map 是一种无序的键值对的集合。map 最重要的一点是通过 key 来快速检索数据,key 类似于索引,指向数据的值。map 是无序的,我们无法决定它的返回顺序,这是因为 map 是使用 hash 表来实现的。map 的 hash 表包含了一个桶集合(collection of buckets)。当我们存储,移除或者查找键值对(key/value pair)时,都会从选择一个桶开始。在映射(map)操作过程中,我们会把指定的键值(key)传递给 hash 函数(又称散列函数)。hash 函数的作用是生成索引,索引均匀的分布在所有可用的桶上。

根据上面的描述是不是可以在其他语言中想到键值对、字典类型?说白了就是python中的dict,这也是为什么我在标题上加上map字典的原因,只是为了便于理解。在性能上来说,map查找比线性搜索快很多,但比使用索引访问数据的类型慢100倍。key必须是支持= =或!=比较运算的类型,不可以是函数、map或slice。

一、创建map

可以通过将键和值的类型传递给内置函数 make 来创建一个 map。语法为:make(map[KeyType]ValueType)。这里我们创建一个员工名称和薪水的对应map的示例为personSalary := make(map[string]int) ,那如何往该map里写入数据呢?插入元素给 map 的语法与数组相似。下面的代码插入一些新的元素给 map personSalary。

 1package main
 2import (
 3    "fmt"
 4)
 5func main() {
 6    personSalary := make(map[string]int)
 7    personSalary["steve"] = 12000
 8    personSalary["jamie"] = 15000
 9    personSalary["mike"] = 9000
10    fmt.Println("personSalary map contents:", personSalary)
11}
12# 执行上面的代码输出结果为
13personSalary map contents: map[steve:12000 jamie:15000 mike:9000]

也可以在声明时初始化一个数组,以下输出结果会和上面的一样:

 1package main
 2import (
 3    "fmt"
 4)
 5func main() {
 6    personSalary := map[string]int {
 7        "steve": 12000,
 8        "jamie": 15000,
 9    }
10    personSalary["mike"] = 9000
11    fmt.Println("personSalary map contents:", personSalary)
12}

string 并不是可以作为键的唯一类型,其他所有可以比较的类型,比如,布尔类型,整型,浮点型,复数类型都可以作为键。具体可以参看官方说明:http://golang.org/ref/spec#Comparison_operators

二、访问map中的元素

map中的元素是跟据键进行获取的,具体语法为:map[key]。如果一个键不存在map 会返回值类型的 0 值。比如如果访问了 personSalary 中的不存在的键,那么将返回 int 的 0 值,也就是 0。

 1package main
 2import (
 3    "fmt"
 4)
 5func main() {
 6    personSalary := map[string]int{
 7        "steve": 12000,
 8        "jamie": 15000,
 9    }
10    personSalary["mike"] = 9000
11    employee := "jamie"
12    fmt.Println("Salary of", employee, "is", personSalary[employee])
13    fmt.Println("Salary of joe is", personSalary["joe"])
14}
15输出结果为
16Salary of jamie is 15000
17Salary of joe is 0

上面的程序返回 joe 的工资为 0。我们没有得到任何运行时错误说明键 joe 在 personSalary 中不存在。我们如何检测一个键是否存在于一个 map 中呢?可以使用下面的语法:

1value, ok := map[key]

上面的语法可以检测一个特定的键是否存在于 map 中。如果 ok 是 true,则键存在,value 被赋值为对应的值。如果 ok 为 false,则表示键不存在。具体示例如下:

 1package main
 2import (
 3    "fmt"
 4)
 5func main() {
 6    personSalary := map[string]int{
 7        "steve": 12000,
 8        "jamie": 15000,
 9    }
10    personSalary["mike"] = 9000
11    newEmp := "joe"
12    value, ok := personSalary[newEmp]
13    if ok == true {
14        fmt.Println("Salary of", newEmp, "is", value)
15    } else {
16        fmt.Println(newEmp,"not found")
17    }
18}

三、map中元素的遍历

range for 可用于遍历 map 中所有的元素,但值得注意的是,因为 map 是无序的,因此对于程序的每次执行,不能保证使用 range for 遍历 map 的顺序总是一致的。

 1package main
 2import (
 3    "fmt"
 4)
 5func main() {
 6    personSalary := map[string]int{
 7        "steve": 12000,
 8        "jamie": 15000,
 9    }
10    personSalary["mike"] = 9000
11    fmt.Println("All items of a map")
12    for key, value := range personSalary {
13        fmt.Printf("personSalary[%s] = %d\n", key, value)
14    }
15}
16# 上面的代码执行后的结果如下
17All items of a map
18personSalary[mike] = 9000
19personSalary[steve] = 12000
20personSalary[jamie] = 15000

四、map元素的删除

delete(map, key) 用于删除 map 中的 key。delete 函数没有返回值。

 1package main
 2import (
 3    "fmt"
 4)
 5func main() {
 6    personSalary := map[string]int{
 7        "steve": 12000,
 8        "jamie": 15000,
 9    }
10    personSalary["mike"] = 9000
11    fmt.Println("map before deletion", personSalary)
12    delete(personSalary, "steve")
13    fmt.Println("map after deletion", personSalary)
14}
15#程序执行的结果如下
16map before deletion map[steve:12000 jamie:15000 mike:9000]
17map after deletion map[mike:9000 jamie:15000]

五、map的大小引用和比较

用内置函数 len 获取 map 的大小,如fmt.Println(“length is”, len(personSalary)) 。与slic切片一样,map 是引用类型。当一个 map 赋值给一个新的变量,它们都指向同一个内部数据结构。因此改变其中一个也会反映到另一个

 1package main
 2import (
 3    "fmt"
 4)
 5func main() {
 6    personSalary := map[string]int{
 7        "steve": 12000,
 8        "jamie": 15000,
 9    }
10    personSalary["mike"] = 9000
11    fmt.Println("Original person salary", personSalary)
12    newPersonSalary := personSalary
13    newPersonSalary["mike"] = 18000
14    fmt.Println("Person salary changed", personSalary)
15}
16# 输出结果如下
17Original person salary map[steve:12000 jamie:15000 mike:9000]
18Person salary changed map[jamie:15000 mike:18000 steve:12000]

上面的程序中,personSalary 赋值给 newPersonSalary。下一行,将 newPersonSalary 中 mike 的工资改为 18000。那么在 personSalary 中 mike 的工资也将变为 18000。

map 不能通过 = = 操作符比较是否相等。= = 操作符只能用来检测 map 是否为 nil。下面的程序执行将会报错:invalid operation: map1 = = map2 (map can only be compared to nil)。

 1package main
 2func main() {
 3    map1 := map[string]int{
 4        "one": 1,
 5        "two": 2,
 6    }
 7    map2 := map1
 8    if map1 == map2 {
 9    }
10}

比较两个 map 是否相等的方式是一一比较它们的元素是否相等。