This question already has an answer here:
This must be a noob question. I was trying to increment a var inside a struct/instance (A.a) after getting the element from a range loop. Looks like I get a copy of the element, how can I reference the element itself on a range loop?
package main
import "fmt"
type A struct {
a int
s string
}
func main() {
var es = []A {
A{
a:0,
s:"test",
},
A{
a:1,
s:"test1",
},
}
for _,e:=range es {
fmt.Printf("%v
", e)
e.a++
}
for _,e:=range es {
fmt.Printf("%v
", e)
e.a++
}
}
Output:
{0 test}
{1 test1}
{0 test}
{1 test1}
Desired output:
{0 test}
{1 test1}
{1 test}
{2 test1}
Thanks in advance
</div>
All assignments in Go are a copy. Use a pointer to modify the original value:
var es = []*A{
&A{
a: 0,
s: "test",
},
&A{
a: 1,
s: "test1",
},
}
https://play.golang.org/p/pz8PwEviMwm
Or alternatively, don't copy the value at all
for i := range es {
fmt.Printf("%v
", es[i])
es[i].a++
}
for i := range es {
fmt.Printf("%v
", es[i])
es[i].a++
}