SoFunction
Updated on 2025-03-05

Go language traversal map implementation (accessing every key-value pair in the map)

The traversal process of map is completed using a for range loop, and the code is as follows:

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

Traversal is similar for many Go language objects. You can just use the for range syntax. When traversing, you can get both keys and values. If you only traversal values, you can use the following form:

for _, v := range scene {

Change the unwanted keys to anonymous variable form.

When traversing only the keys, use the following form:

for k := range scene {

There is no need to change the value to anonymous variable, just ignore the value.
Note: The order of traversing the output elements has nothing to do with the order of filling, and you cannot expect map to return a result of some expected order when traversing.

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

scene := make(map[string]int)
// Prepare map datascene["route"] = 66
scene["brazil"] = 4
scene["china"] = 960
// Declare a slice to save map datavar sceneList []string
// Copy map data traversal into slicesfor k := range scene {
  sceneList = append(sceneList, k)
}
// Sort the slices(sceneList)
// Output(sceneList)

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

The code description is as follows:

  • Line 1 creates a map instance with the key as a string and the value as an integer.
  • Lines 4 to 6, write 3 key-value pairs into the map.
  • Line 9, declare sceneList as a string slice to buffer and sort all elements in the map.
  • Line 12: Iterate out the keys of the elements in the map and put them into the slice.
  • Line 17: Sorting the sceneList string slices. When sorting, sceneList will be modified.
  • Line 20, output the key of the sorted map.

The function is to arrange the string characters in ascending order of the passed string slices. The use of the sorting interface will be introduced in the following chapters.

This is the article about Go language traversal map implementation (visiting every key-value pair in the map). For more related Go language traversal map content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!