Go 指南学习笔记六

1.map

map在使用之前必须使用make来创建,值为nil的map是空的,并且不能对它赋值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package main
import (
"fmt"
)
type Vertex struct{
Lat, Long float64
}
var m map[string]Vertex
func main() {
m = make(map[string]Vertex)
m["Bell Labs"] = Vertex{40.68433, -74.39967}
fmt.Println(m["Bell Labs"])// {40.68433 -74.39967}
}

2.和结构体语法类似

1
2
3
4
5
var n = map[string]Vertex {
"Bell Labs": Vertex{40.68433, -74.39967,},
"Google":Vertex{37.42202, -122.08408,},
}
fmt.Println(n) //map[Bell Labs:{40.68433 -74.39967} Google:{37.42202 -122.08408}]

如果map的value值只是一个类型,可以在{}中将类型省略

1
2
3
4
var k = map[string]Vertex{
"Bell Labs": {40.68433, -74.39967},
"Google": {37.42202, -122.08408},
}

3.修改map

  • 插入或者修改元素: m[key] = elem
  • 获得元素: elem = m[key]
  • 删除元素: delete(m,key)
  • 检测是否存在: elem, ok = m[key]
如果您觉得对您有帮助,谢谢您的赞赏!