SoFunction
Updated on 2025-04-12

Several ways to traverse the loop in Go language

In Go language, traversal loops are mainly used to iterate over data structures such as arrays, slices, maps, and strings. Go provides two main ways of traversing:for Loop and for rangeStructure. The following is a detailed introduction to these two methods and discuss some things to pay attention to when using them.

Use for loop traversal

The most basic way to traverse is to access elements in an array or slice through indexes. For example:

arr := [5]int{1, 2, 3, 4, 5}
for i := 0; i < len(arr); i++ {
    ("Index:", i, "Value:", arr[i])
}

This approach is suitable for situations where both index and value are required.

Use for range to traverse

rangeProvides a more concise way to traverse arrays, slices, strings, maps and other data structures. It returns two values: the first is the index of the current element (a key for map), and the second is the value of the element. Unwanted return values ​​can be ignored, just provide an underscore_Placeholder.

Array/Slice Traversal

numbers := []int{1, 2, 3, 4, 5}
for index, value := range numbers {
    ("Index: %d, Value: %d\n", index, value)
}

If only indexes or values ​​are needed, another variable can be omitted:

// Only care about indexesfor index := range numbers {
    ("Index:", index)
}

// Only care about the valuefor _, value := range numbers {
    ("Value:", value)
}

String traversal

rangeIt can also be used to traverse strings, and what is returned is the byte index of the character and the corresponding character.

str := "Hello"
for index, char := range str {
    ("Index: %d, Character: %c\n", index, char)
}

Map traversal

When iterating over maps,rangeThe returned key-value pair:

m := map[string]string{"apple": "red", "banana": "yellow"}
for key, value := range m {
    ("Key: %s, Value: %s\n", key, value)
}

It is worth noting that since map is an unordered collection, the order of output during traversal is not necessarily the same as the order of insertion.

Things to note

In usefor rangeWhen performing traversal, developers may encounter some common pitfalls, such as variable scope problems. For example, when you try to store the address of a loop variable, all stored pointers actually point to the same memory location, which can lead to unexpected behavior. The correct way to do this is to create a new variable to save the results of each iteration.

In addition, use in concurrent environmentsfor rangeBe careful when it comes to goroutines, as loop variables are shared in all goroutines, which may lead to race conditions. One way to solve this problem is to declare new local variables within the loop body, or pass the value directly instead of referring to the goroutine.

In summary,forandfor rangeIt is a very powerful and flexible tool in the Go language that can help you effectively traverse various data structures. A proper understanding of how they work and potential problems can help you write more robust and efficient code.

This is the end of this article about several methods of Go language traversal loops. For more related content on Go language traversal loops, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!