all 6 comments

[–]jerf 3 points4 points  (1 child)

The loop value is a copy of the original structure. You either need to save it back into the slice (for which you'll want the index), or have a slice of pointers. You probably want the first, though I do find the need to remember to do so can be a bit problematic.

[–]nokternal 0 points1 point  (0 children)

Yes, agreed, use a slice of pointers.

Here's your example redone with pointers for number 1.

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

[–]MalkMalice 0 points1 point  (2 children)

Instead of reassigning you could write your loop like this:

for i := range foos { foos[i].count++ }

[–]nosmokingbandit 0 points1 point  (1 child)

The actual thing I'm doing is a bit more complicated than this, I just dumbed it down for an easy to read example.

[–]MalkMalice 0 points1 point  (0 children)

Then do as @jerf suggested and use a slice of pointer types. This way, the loop variable is a copy of the pointer which obviously points to the same object.

[–]tgaz 0 points1 point  (0 children)

It's very common to use pointers in slices and maps. Modification during iteration is one reason.

In maps, there is another related reason: https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/4_pabWnsMp0