GeekCoding101 make your way to geek

Golang Range Loop Pointer: Same Address Bug & Go 1.22 Fix

Why &v in a Go for-range loop gave every pointer the same address, what Go 1.22 changed, and why &slice[i] is still the fix when you need the original.

6 min read
Feature Image 1
On this pageOn this page

Before Go 1.22, for _, v := range s reused one variable v for the whole loop, so &v returned the same address on every iteration and every stored pointer ended up showing the last element. Go 1.22 gives each iteration its own v, but &v still points to a copy, not the element in your slice. When you need a pointer to the real element, use &s[i].

When I first started learning Go, I hit this exact bug. I was iterating over a slice of Book structs, taking a pointer to each one and storing them in another slice. At the end of the loop, every pointer pointed to the same book. 🤯

(The structs and code here are written for this tutorial, not taken from a real project.)

Let’s walk through this classic Go mistake, see why it happens, and fix it the right way.

On this page

  • The use case: a slice of books
  • File structure and how to run it
  • The problem: one loop variable, one address
  • What changed in Go 1.22 (and what didn’t)
  • The fix: index directly
  • Quick comparison of the options
  • Code on GitHub
  • FAQ

📚 The Use Case: A Slice of Books

Suppose we have a list of books, and we want to collect pointers to each one so we can modify them later.

Here’s the code I thought would work:

for _, book := range books {
bookPointers = append(bookPointers, &book) // Oops...
}

When I printed the pointers, they all pointed to the last book in the list. The bug stumped me for a while, until I understood how Go handles the range loop variable.

The File Structure to Run the Code

learning-golang/
├── 01-loop-reference-pitfall/
│ ├── main.go
│ └── README.md
├── Makefile
├── bin/
└── go.mod

This is the complete buggy code:

package main
import (
"fmt"
)
type Book struct {
Title string
Author string
}
func main() {
originalBooks := []Book{
{"Go in Action", "William Kennedy"},
{"The Go Programming Language", "Alan Donovan"},
{"Introducing Go", "Caleb Doxsey"},
}
fmt.Println("❌ Buggy Version:")
var buggyPointers []*Book
for _, book := range originalBooks {
buggyPointers = append(buggyPointers, &book)
}
for _, bp := range buggyPointers {
fmt.Printf("Title: %-30s | Address: %p\n", bp.Title, bp)
}
}

The Makefile:

# Usage:
# make run DIR=01-loop-reference-pitfall
# make build DIR=01-loop-reference-pitfall
# make clean
GO=go
run:
@echo "👉 Running $(DIR)/main.go..."
cd $(DIR) && $(GO) run main.go
build:
@echo "🔧 Building binary from $(DIR)/main.go..."
cd $(DIR) && $(GO) build -o ../bin/$(notdir $(DIR))
clean:
@echo "🧹 Cleaning up built binaries..."
rm -rf bin/

Build and Run the Code

Terminal window
❯ go mod init github.com/geekcoding101/learning-golang
❯ make run DIR=01-loop-reference-pitfall

Golang Range Loop Reference - First time build and run code
Golang Range Loop Reference - First time build and run code

As you can see, the address doesn’t change at all.

Can’t reproduce it? The old behaviour depends on the go line in your go.mod. A recent toolchain writes its own version there during go mod init, so with Go 1.22 or newer you’ll see different addresses. To see the original bug, set the directive to an older version:

go 1.21

🐛 The Problem: One Loop Variable, One Address

In Go before 1.22, when you write:

for _, book := range books

the book variable is declared once and reused in every iteration. It’s not a new instance each time. Each pass copies the next element into that same variable, so &book gives you the same memory address over and over.

Every pointer in the slice ends up pointing to that one location. After the loop finishes, that location holds a copy of the last book.

🔄 What Changed in Go 1.22 (and What Didn’t)

Since Go 1.22, each iteration of a for loop gets its own fresh variable, for modules whose go.mod declares go 1.22 or later. With that version, the buggy code above prints three different addresses and three different titles.

The pointers still don’t point into originalBooks. Each book is a copy of the element, so modifying the book through those pointers leaves the original slice untouched:

buggyPointers[0].Title = "Changed!"
fmt.Println(originalBooks[0].Title) // still "Go in Action"

My goal was to collect pointers so I could modify the books later. So even on current Go, &book is the wrong tool for this job.

Go 1.21 and earlierGo 1.22 and later
Loop variableOne variable, reused every iterationA new variable per iteration
&book addressesAll the sameAll different
What &book points toA copy, holding the last book at the endA copy of each book
Changes visible in originalBooks?NoNo

✅ The Fix: Index Directly

The correct way is to take the address of the slice element itself, using its index:

fmt.Println("\n✅ Fixed Version:")
var fixedPointers []*Book
for i := range originalBooks {
fixedPointers = append(fixedPointers, &originalBooks[i])
}
for _, bp := range fixedPointers {
fmt.Printf("Title: %-30s | Address: %p\n", bp.Title, bp)
}

Now each pointer refers to the corresponding element in the original slice, on any Go version. A change made through fixedPointers[0] shows up in originalBooks[0]. Problem solved!

second time with fix build and run
second time with fix build and run

One caveat: if you later append to originalBooks and Go has to grow the slice, it copies the elements to a new backing array. Your saved pointers keep pointing at the old array, so take them after the slice has stopped growing.

⚖️ Quick Comparison of the Options

PatternDistinct pointers?Points to the original element?
&book in for _, book := range (before Go 1.22)NoNo
&book in for _, book := range (Go 1.22+)YesNo, a copy
book := book inside the loop (old workaround)YesNo, a copy
&originalBooks[i] with for i := rangeYesYes
Start with []*Book instead of []BookYesYes, the pointers are the data

💻 Code on GitHub

I’ve documented this bug and fix in my GitHub repository:

👉 github.com/geekcoding101/learning-golang

What you’ll find:

  • The buggy version, with all pointers pointing to the same book
  • The fixed version, with each pointer referring to the correct element
  • A Makefile to help you run and build each learning topic

❓ FAQ

Why does my Go loop store the same pointer every time? In Go before 1.22, the range variable is a single variable reused for every iteration, so &v always returns the same address. Check the go line in your go.mod. Below 1.22, you get the old behaviour.

Is this bug fixed in Go 1.22? The “same address” part is fixed: each iteration now gets its own variable. But &v still points to a copy of the element, so if you want to modify the original slice, you still need &s[i].

How do I correctly get a pointer to a slice element in a loop? Loop over the index with for i := range s and take &s[i]. That address is the element inside the slice’s backing array.

Does v := v inside the loop fix it? It gives you a distinct pointer per iteration, which was the common workaround before Go 1.22. It’s still a pointer to a copy, though, so changes won’t reach the original slice.

✍️ More Go Notes

I’ll keep sharing hands-on lessons like this as I go deeper into Go. More practical posts are on GeekCoding101.

Thanks for reading my blog post! Feel free to check out my other posts or contact me via the social links in the footer.

Keep reading

All posts