Loop & Pointer in Go (golang): small trap with big consequences.

Wacław The Developer
1 min readDec 12, 2021
Photo by Brett Jordan on Unsplash

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:

  1. elem variable will be created
  2. elem = sourceArray[0]
  3. elem = sourceArray[1]
  4. 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 :)

--

--