Call struct method in range loop


example code (edited code snippet):

Why is it that

for x, _ := range body.Personality {

successfully mutates the structs’ contents, but

for _, pf := range body.Personality{

does not?
Is it that range creates new instances of each item it iterates over? because the struct does in fact mutate but it doesn’t persist.


The range keyword copies the results of the array, thus making it impossible to alter the
contents using the value of range. You have to use the index or a slice of pointers instead of values
if you want to alter the original array/slice.

This behaviour is covered by the spec as stated here. The crux is that an assignment line
x := a[i] copies the value a[i] to x as it is no pointer. Since range is defined to use
a[i], the values are copied.

Answered By – nemo

Answer Checked By – Willingham (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.