Start learning free

LESSON 181 OF 671 · LOOPING OVER ARRAY INDICES

Manipulating Array Elements Inside a For Loop in Go

Lesson

Suppose you have an array nums and your task is to increment every number in that array by one.

The first idea that might come to your mind is to write a for loop like this:

nums := []int{1, 2, 3}

// Increment items:
for _, num := range nums {
  num++
}

// Print the array after:
for _, num := range nums {
  fmt.Println(num)
}

but when you run this code, you'll be surprised to see that the output is:

1
2
3

No element in nums changed its value. How is this possible since we clearly do num++ for every num in nums?


Let's talk about copies:

Take a look at this code:

number := 100

numberCopy := number

numberCopy++

fmt.Println(numberCopy) // Output: 101
fmt.Println(number) // Output: 100

Although we wrote numberCopy := number, this doesn't mean that number and numberCopy are one and the same.

numberCopy is a completely different entity (stored at a different memory address) than number.

What we did is initialize this new numberCopy entity with the value of number. That's why we say the numberCopy is a copy of number.

And so numberCopy++ will only increment numberCopy and won't have any effect on number.


The loop variable is just a copy:

This is what also happens with a for loop.

Whenever you write a for loop, the loop variable (in our case num) is just a copy of the current item of the array, not the item itself.

This code

nums := []int{1, 2, 3}

for _, num := range nums {
  num++
}

works exactly like this code:

nums := []int{1, 2, 3}

num := nums[0]
num++

num = nums[1]
num++

num = nums[2]
num++

Notice that only the variable num is being manipulated, which has nothing to do with the actual entries of the array nums.

You'll see this better if we also print the value of num on each iteration.

nums := []int{1, 2, 3}

for _, num := range nums {
  num++
  fmt.Println(num)
}

// Print the array after:
for _, num := range nums {
  fmt.Println(num)
}

The output of this code is:

2
3
4
1
2
3

Looping over the indices:

In order to manipulate the entries of some array we have to loop over the items' indices:

nums := []int{1, 2, 3}

for index := 0; index < len(nums); index++ {
  nums[index]++
}

This code works exactly like this one:

nums := []int{1, 2, 3}

index := 0
nums[index]++

index++
nums[index]++

index++
nums[index]++

In this way we directly manipulate the actual entries of the slice (nums[0], nums[1], etc.)

Assignment:

Fix our code such that it correctly increments (adds one to) the even numbers of nums and decrements (subtracts one from) the odd ones.

STEP 1 OF 1
    Ctrl + Enter to check