0

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\n", e)
    e.a++
  }
  for _,e:=range es {
    fmt.Printf("%v\n", 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

martin
  • 862
  • 9
  • 28

1 Answers1

7

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\n", es[i])
    es[i].a++
}
for i := range es {
    fmt.Printf("%v\n", es[i])
    es[i].a++
}

https://play.golang.org/p/EGl1INcBaTI

JimB
  • 104,193
  • 13
  • 262
  • 255