Loop & Pointer in Go (golang): small trap with big consequences.
1 min readDec 12, 2021
Hi everyone! Today i will show you some tricks with loops and pointer. Take a look at this code:
Try to say what will be printed after execution?
The answer is:
third
third
third
But why?
So, let’s try to print original slice with details:
package main
import "fmt"
func main() {
sourceArray := []string{"first", "second", "third"}
for i, elem := range sourceArray {
fmt.Printf("Index: %d, element: %s, pointer: %p \n", i, elem, &elem)
}
}
The output will be like that:
Index: 0, element: first, pointer: 0x14000010230
Index: 1, element: second, pointer: 0x14000010230
Index: 2, element: third, pointer: 0x14000010230
That’s because loop with range creates elem variable and re-uses it to iterate the elements.
So, what will be in loop:
- elem variable will be created
- elem = sourceArray[0]
- elem = sourceArray[1]
- elem = sourceArray[2]
As result, &elem points to memory with the last iterated element (“third”).
Fix: use the index
Conclusion:
I hope someone will avoid bugs in code :)