0

I have a struct array of type []Struct. When I range over it in the form:

for i, val := range mystructarray

I understand that val is a local variable which contains a copy of mystructarray[i]. Is there a better way of iterating through the addressess of mystructarray than this:

for i := range mystructarray{
    valptr = &mystructarray[i]
}

?

ealfonso
  • 6,622
  • 5
  • 39
  • 67
  • possible duplicate of [Change values while iterating in golang](http://stackoverflow.com/questions/15945030/change-values-while-iterating-in-golang) – Denys Séguret Sep 09 '14 at 14:11
  • The answer to the questions may overlap, but that question is really asking about a different issue. Someone who comes to the site looking for an answer to my question won't necessarily find the other one. – ealfonso Sep 09 '14 at 14:17

1 Answers1

1

There is no way to iterate while receiving a pointer to the contents of the slice (unless of course, it is a slice of pointers).

Your example is the best way:

for i := range mySlice {
    x = &mySlice[i]
    // do something with x
}

Remember however, if your structs aren't very large, and you don't need to operate on them via a pointer, it may be faster to copy the struct, and provide you with clearer code.

JimB
  • 104,193
  • 13
  • 262
  • 255