Go 语言 map (映射)

1、Go 语言中 map 的定义及初始化:

1 map[Key_Type]Value_Type
2 scence := make(map[string]int)

2、Go 语言的遍历:

1 scene := make(map(string)int)
2 for k, v := range scene {}

2.1 只遍历键或值时

1 for k :=range scene {     #无需将值匿名
2 for _, v := range scene {  #将不要的键匿名

2.2 如果需要特定的遍历结果,正确的做法是排序

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "sort"
 6 )
 7 
 8 func main() {
 9     scene := make(map[string]int)
10     scene["route"] = 66
11     scene["brazil"] = 4
12     scene["china"] = 960
13 
14     var sceneList []string
15     for k := range scene {
16         sceneList = append(sceneList, k)
17     }
18 
19     sort.Strings(sceneList)
20     fmt.Println(sceneList)
21 }

3、使用 delete() 函数从 map 中删除键值对

1 delete(map, 键)

      Go 语言中并没有为 map 提供任何一个清空所有元素的函数、方法。清空 map 的唯一方法就是重新 mak 一个新的 map。

猜你喜欢

转载自www.cnblogs.com/prometheus-python-xshell/p/10748832.html