1

In this example on the go playground, you can see that looping over a list of objects and putting them into an array of pointer structs ends up putting the same entry into the array multiple times.

http://play.golang.org/p/rICA21kFWL

One possible solution to the issue is to make a new string and sprint the string out of the looped string into the new string. This seems silly though.

What is the idiomatically correct way to handle this problem?

Case
  • 1,848
  • 21
  • 32

1 Answers1

1

In case I understood correctly and you simply want an array of pointers pointing to the respective string in the original array, you can always do this

# choose correct size from beginning to avoid costly resize
o := make([]*string, len(f))

# iterate only over index
for i := range f {
    o[i] = &f[i].username
}

Here's your go playground with the changes sketched out above.

panmari
  • 3,627
  • 3
  • 28
  • 48
  • This would assume that the thing I'm ranging over is indexable. Unfortunately it isn't -- I'm pulling from a sql results object with Next(). I could dump the sql results into a regular non-pointer array first, but that also does not seem idiomatically correct. – Case Jul 11 '14 at 21:12
  • In that case, you might have to settle with something like this: http://play.golang.org/p/ssLVP4aCsj, just copy the value you're interested in to some temp variable and take the pointer of it. – panmari Jul 11 '14 at 21:21
  • Incidentally, strings are already references to immutable data in Go, so copying them is about equally cheap if you just use a `[]string` rather than a `[]*string`. Also references: slices like `[]byte` and some other important types in Go; see http://research.swtch.com/godata for a description of some of the structures and http://stackoverflow.com/questions/23542989/best-practice-returning-structs-in-go/23551970 for my best go at summarizing when you should/shouldn't use pointers. – twotwotwo Jul 13 '14 at 00:19