For-range creates a circular perpetual motion machine? Come take a look at those things about for-range in go!

From the public account: New World Grocery Store

Cyclic perpetual motion machine

Q1: If we modify the array elements while traversing the array, can we get a loop that never stops?

func main() {
    
    
 arr := []int{
    
    1, 2, 3}
 for _, v := range arr {
    
    
     arr = append(arr, v)
 }
 fmt.Println(arr)
}
// 输出: 1 2 3 1 2 3

The output of the above code means that the loop only traverses the three elements in the original slice. The additional elements when we traverse the slice will not increase the number of executions of the loop, so the loop eventually stops.

Answer: For all range loops, Go language will assign 原切片or 数组assign to a new variable during compilation, and hacopy occurs during the assignment process, so the slice we traverse is no longer the original slice variable

Magic pointer

Q2: When we traverse an array, if we get rangethe address of the return variable and save it to another array or hash, we will encounter a confusing phenomenon

func main() {
    
    
    arr := []int{
    
    1, 2, 3}
    newArr := []*int{
    
    }
    for _, v := range arr {
    
    
        newArr = append(newArr, &v)
    }
    for _, v := range newArr {
    
    
        fmt.Println(*v)
    }
}
// 输出: 3 3 3

Answer: When encountering this kind of range loop that traverses the index and the elements at the same time, the Go language will additionally create a new v2variable to store the elements in the slice 循环中使用的这个变量v2会在每一次迭代被重新赋值而覆盖, 在赋值时也发生了拷贝. Because the addresses of the variables returned in the loop are exactly the same, the magic appears The phenomenon of pointers

Random traversal of the map

Q3: When using range to traverse the hash table in go language, often get different results?

Answer: But this does not mean that the hash table is unstable. This is designed by the go language deliberately. It introduces uncertainty for the hash table traversal at runtime, and it also tells all users of the go language that the program should not rely on Stable traversal of the hash table.

reference

https://draveness.me/golang/docs/part2-foundation/ch05-keyword/golang-for-range/

Guess you like

Origin blog.csdn.net/u014440645/article/details/108850385