This article transferred from: https://www.cnblogs.com/demon89/p/7259724.html
Map is a collection of unordered key-value pairs. The most important point of MAP is to quickly retrieve the data by key, which is similar to the index, which points to the value of the data.
Map is a collection, so we can iterate over it like an iterative algebraic group and a slice. However, map is unordered, and we cannot determine the order in which it is returned because the map is implemented using a hash table.
所以在golang中Map的遍历不像其他语言一样,它的输出是无序的func traversal() { tmap := make(map[int]string) tmap[0] = "a" tmap[1] = "b" tmap[2] = "c" tmap[3] = "d" tmap[4] = "e" tmap[5] = "f" tmap[6] = "g" tmap[7] = "h" for k, v := range tmap { fmt.Printf("k:%d,v:%s\n", k, v) }}output:k:2,v:ck:3,v:dk:4,v:ek:5,v:fk:6,v:gk:7,v:hk:0,v:ak:1,v:b
He wanted to print it in order.
//创建mapcountryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo","India":"New Delhi"}country_array := [] string {"France","Italy","Japan","India"} //根据自定义的数组的顺序有序的打印map中的信息for _,country := range country_array{ fmt.Printf("Capital %v of is %v \n",country,countryCapitalMap[country])}
Then I saw that brother was so stubborn that I stopped by and looked at how to sort a map
In fact, the idea is the same, can only use slice curve to salvation.
func main() { m := map[string]int{ "something": 10, "yo": 20, "blah": 20, } type kv struct { Key string Value int } var ss []kv for k, v := range m { ss = append(ss, kv{k, v}) } sort.Slice(ss, func(i, j int) bool { return ss[i].Value > ss[j].Value // 降序 // return ss[i].Value < ss[j].Value // 升序 }) for _, kv := range ss { fmt.Printf("%s, %d\n", kv.Key, kv.Value) }}
Define Map
You can use the built-in function make or you can use the Map keyword to define a map:
声明变量,默认map是nilvar map_name = map[type]type另外一种使用make创建map_name := make(map[type]type)
If you do not initialize the map, a nil map is created. Nil map cannot be used to store key value pairs
One of the most common and noteworthy considerations is whether a key exists in the map
//To see if the element is in map, the variable OK returns TRUE or false,//when the key of the query returns true in the map and captial gets the value in the map captial, OK: = countrycapitalmap["states"]if ok{FMT. Println ("Capital of", Captial, "is", countrycapitalmap[captial])}else{FMT. Println ("Capital of the states is not present")}