0

There is something wrong with the compiler or my understanding of Go. I have a weird bug and have whittled it down to a simple example. For some reason I can't change the array directly within a loop.

    var nums [2]int
    for i, v := range nums {
        if i == 0 {
            nums[i+1]++
        } else {
            fmt.Print(v)
        }
    }

This increments nums[1] then prints it. So it should print 1 but it prints 0.

3
  • 2
    Rule of thumb: Using an array is probably wrong in Go. Commented Sep 5, 2019 at 13:13
  • @Volker You're mistaken - no such rule exists Commented Sep 5, 2019 at 20:18
  • That's why the rule is on your thumb! In all seriousness, Arrays are fine for static definitions (see go's time pkg for days of the week) - but for mutable values, slices are preferred. If you need a certain size, prealloc the slice with make. Commented Sep 6, 2019 at 19:37

2 Answers 2

4

When you use an array in an expression you get its "value" (ie, a complete new copy of the array). This includes using an array in the range expression of a loop. So when you print v you are printing the copy, but the actual nums array has been changed.

Looping on a slice instead of the array gives you what you expect:

    var nums [2]int
    for i, v := range nums[:] {
        if i == 0 {
            nums[i+1]++
        } else {
            fmt.Print(v)
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

2

The range creates a copy of the array (and its values), so it can iterate over them.

If you plan on mutating an array (or a slice of that matter) during iteration, it's best to reference the array/slice directly - as the v value will be a copy and in your code an old copy of the array.

So try something like:

var nums [2]int
for i := range nums {
    if i == 0 {
        nums[i+1]++
    } else {
        fmt.Print(nums[i])
    }
}

Playground

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.