Occlusion effect of for loop in Go

Note: Occlusion is not replacement

In a for loop, if we declare a variable with the same name as the variable in the initialization statement inside the loop body, then this new variable will "shadow" the outer variable with the same name. But this occlusion is only valid from the beginning of the line of code that declares it until the end of the loop body. When the next loop starts, the outer variable of the same name reappears and continues to use the value in the for statement.

Think of forthe variable in the loop ias a light bulb in a room, and i := ithis line of code is like placing a screen in the corner of the room to block the light.

for i := 0; i < 3; i++ {
    
    
	fmt.Println("before:", i)
	i := i
	i = 100
	fmt.Println("after:", i)
}

output:

before: 0
after: 100
before: 1
after: 100
before: 2
after: 100

Guess you like

Origin blog.csdn.net/qq_35760825/article/details/132205273