If you iterate over a slice using the range operator you will get a copy of the value and not a pointer to it. This is also true for maps.

You can find more infos about this here. If you want to change the contents of the original slice you will have to access the slice using indices. I have prepared a small example below (run it at the Go Playground):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package main

import (
	"fmt"
)

type POI struct {
	Name string
}

func main() {
	var pois []POI
	poi := POI{Name: "ORIGINAL"}
	pois = append(pois, poi)
	fmt.Printf("Original struct content ---> %+v\n", pois)

	// DOES NOT WORK
	alterStructWithRange(pois)
	fmt.Printf("After calling alterStructWithRange() ---> %+v\n", pois)

	// WORKS
	alterStructWithRangeAndIdx(pois)
	fmt.Printf("After calling alterStructWithRangeAndIdx() ---> %+v\n", pois)
}

// DOES NOT WORK
func alterStructWithRange(pois []POI) {
	for _, poi := range pois {
		poi.Name = "alterStructWithRange"
	}
}

// WORKS
func alterStructWithRangeAndIdx(pois []POI) {
	for i := range pois {
		pois[i].Name = "alterStructWithRangeAndIdx"
	}
}

This is the output of the program:

Original struct content ---> [{Name:ORIGINAL}]
After calling alterStructWithRange() ---> [{Name:ORIGINAL}]
After calling alterStructWithRangeAndIdx() ---> [{Name:alterStructWithRangeAndIdx}]

A note about Netcup (advertisement)

Netcup is a German hosting company. Netcup offers inexpensive, yet powerfull web hosting packages, KVM-based root servers or dedicated servers for example. Using a coupon code from my Netcup coupon code web app you can even save more money (6$ on your first purchase, 30% off any KVM-based root server, ...).