Go language traverses the map implementation (accessing each key value pair in the map)

Time:2022-5-10

The traversal process of map is completed by using the for range loop. The code is as follows:


scene := make(map[string]int)
scene["route"] = 66
scene["brazil"] = 4
scene["china"] = 960
for k, v := range scene {
  fmt.Println(k, v)
}

Traversal is similar to many objects in go language. You can directly use the for range syntax. When traversing, you can obtain keys and values at the same time. If you only traverse values, you can use the following form:


for _, v := range scene {

Use unwanted keys_ Change to anonymous variable form.

When traversing only keys, use the following form:


for k := range scene {

There is no need to change the value to the form of anonymous variable, and the value can be ignored.
Note: the order of traversing the output elements has nothing to do with the filling order. You can’t expect the map to return the results of a desired order during traversal.

If you need traversal results in a specific order, the correct way is to sort first. The code is as follows:

scene := make(map[string]int)
//Prepare map data
scene["route"] = 66
scene["brazil"] = 4
scene["china"] = 960
//Declare a slice to hold map data
var sceneList []string
//Copy map data traversal into slices
for k := range scene {
  sceneList = append(sceneList, k)
}
//Sort slices
sort.Strings(sceneList)
//Output
fmt.Println(sceneList)

The code output is as follows:
[brazil china route]

The code description is as follows:

  • In line 1, create a map instance. The key is a string and the value is an integer.
  • In lines 4 to 6, write three key value pairs into the map.
  • Line 9 declares the scenelist as a string slice to buffer and sort all elements in the map.
  • Line 12, traverse the keys of the elements in the map and put them into the slice.
  • Line 17: sort the scenelist string slice. When sorting, the scenelist will be modified.
  • Line 20, output the keys of the ordered map.

sort. Strings is used to arrange string characters in ascending order for incoming string slices. The use of sorting interface will be introduced in later chapters.

This is the end of this article about the go language traversal map implementation (accessing each key value pair in the map). For more information about go language traversal map, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!