Bird
Raised Fist0
Goprogramming~15 mins

Iterating over arrays in Go - Deep Dive

Choose your learning style10 modes available
Overview - Iterating over arrays
What is it?
Iterating over arrays means going through each item in a list one by one. In Go, arrays are fixed-size collections of elements of the same type. Iteration lets you access or change each element in order. This is useful for tasks like printing values, calculating totals, or modifying data.
Why it matters
Without iteration, you would have to manually access each element by its position, which is slow and error-prone. Iteration automates this process, making programs shorter, easier to read, and less likely to have mistakes. It helps computers handle repetitive tasks efficiently, which is essential for almost all software.
Where it fits
Before learning iteration, you should understand what arrays are and how to declare them in Go. After mastering iteration, you can learn about slices, maps, and more complex data structures that also use iteration. Iteration is a foundation for loops, algorithms, and data processing.
Mental Model
Core Idea
Iterating over arrays is like checking each item in a row one by one to do something with it.
Think of it like...
Imagine you have a row of mailboxes, each with a letter inside. Iterating over the array is like walking down the row and opening each mailbox in order to read or sort the letters.
Array: [a0, a1, a2, a3, ..., an]
Iteration:
Start -> a0 -> a1 -> a2 -> a3 -> ... -> an -> End
Build-Up - 7 Steps
1
FoundationUnderstanding Go arrays basics
šŸ¤”
Concept: Learn what arrays are and how to declare them in Go.
In Go, an array holds a fixed number of elements of the same type. Example: var numbers [3]int = [3]int{10, 20, 30} This creates an array named numbers with 3 integers.
Result
You have a fixed-size list of integers stored in memory.
Knowing arrays are fixed size helps you understand why iteration is needed to access each element.
2
FoundationBasic for loop to access elements
šŸ¤”
Concept: Use a for loop with an index to access each array element.
You can loop over an array using a for loop: for i := 0; i < len(numbers); i++ { fmt.Println(numbers[i]) } This prints each number by index.
Result
Output: 10 20 30
Using an index lets you visit each element in order, which is the core of iteration.
3
IntermediateUsing range for simpler iteration
šŸ¤”Before reading on: do you think 'range' returns just the element or both index and element? Commit to your answer.
Concept: The range keyword simplifies iteration by returning index and value automatically.
Go's range lets you loop over arrays easily: for index, value := range numbers { fmt.Printf("Index %d has value %d\n", index, value) } You can ignore index or value if not needed.
Result
Output: Index 0 has value 10 Index 1 has value 20 Index 2 has value 30
Range reduces boilerplate and mistakes by handling index counting internally.
4
IntermediateIgnoring index or value in range
šŸ¤”Before reading on: do you think you can skip the index or value in range loops? Commit to your answer.
Concept: You can ignore either index or value by using underscore (_) in range loops.
If you only want values: for _, value := range numbers { fmt.Println(value) } If you only want indexes: for index := range numbers { fmt.Println(index) }
Result
Output for values only: 10 20 30 Output for indexes only: 0 1 2
Ignoring unused variables keeps code clean and avoids compiler warnings.
5
IntermediateModifying array elements during iteration
šŸ¤”Before reading on: do you think modifying the value variable in range changes the array? Commit to your answer.
Concept: Modifying the value variable in range does NOT change the original array element; you must use the index to modify the array.
Example: for i, v := range numbers { v = v * 2 // This changes only v, not numbers[i] } To modify the array: for i := range numbers { numbers[i] = numbers[i] * 2 }
Result
After modification, numbers = [20, 40, 60]
Understanding value copies vs references prevents bugs when changing arrays.
6
AdvancedIterating over multi-dimensional arrays
šŸ¤”Before reading on: do you think you can use a single range loop for multi-dimensional arrays? Commit to your answer.
Concept: Multi-dimensional arrays require nested loops to access each element in all dimensions.
Example 2D array: var matrix [2][3]int = [2][3]int{{1,2,3},{4,5,6}} Nested loops: for i, row := range matrix { for j, val := range row { fmt.Printf("matrix[%d][%d] = %d\n", i, j, val) } }
Result
Output: matrix[0][0] = 1 matrix[0][1] = 2 matrix[0][2] = 3 matrix[1][0] = 4 matrix[1][1] = 5 matrix[1][2] = 6
Nested iteration matches the structure of multi-dimensional arrays, enabling full access.
7
ExpertPerformance considerations in array iteration
šŸ¤”Before reading on: do you think range copies the entire array or just elements during iteration? Commit to your answer.
Concept: Range copies the array or slice header but not the entire array; however, value variables are copies of elements, which can affect performance for large structs.
When iterating over large arrays of structs, copying each element can be costly. To avoid this, iterate using pointers: for i := range largeArray { ptr := &largeArray[i] // modify via ptr } This avoids copying each element.
Result
More efficient iteration with less memory overhead.
Knowing how Go handles copies during iteration helps write efficient, low-latency code.
Under the Hood
When you use a for loop with an index, Go accesses each element by calculating its memory address using the base address plus the index times element size. The range keyword creates a copy of the array header (pointer, length, capacity) and iterates over elements by index, assigning each element's value to variables. For value types, this means a copy of the element is made for each iteration. Modifying the value variable does not affect the original array unless you use the index to access and change the element directly.
Why designed this way?
Go was designed for simplicity and safety. Copying values during iteration avoids accidental changes to the original data, preventing bugs. The range syntax balances ease of use with explicit control. Alternatives like pointer iteration exist for performance-critical code. This design avoids hidden side effects and keeps code clear.
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│   Array     │
│ [a0, a1,...]│
ā””ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
      │
      ā–¼
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│  for loop   │
│ i = 0 to n  │
ā””ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
      │
      ā–¼
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ Access a[i] │
│ Copy value  │
ā””ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
      │
      ā–¼
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ Use value   │
│ (print, mod)│
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
Myth Busters - 4 Common Misconceptions
Quick: Does modifying the value variable in a range loop change the original array element? Commit to yes or no.
Common Belief:Modifying the value variable inside a range loop changes the original array element.
Tap to reveal reality
Reality:The value variable is a copy; changing it does not affect the original array element.
Why it matters:Assuming changes affect the array leads to bugs where data is not updated as expected.
Quick: Does range copy the entire array when iterating? Commit to yes or no.
Common Belief:Range copies the entire array before iterating over it.
Tap to reveal reality
Reality:Range copies only the array header (pointer, length, capacity), not the whole array data.
Why it matters:Thinking range copies the whole array can cause unnecessary worry about performance and memory.
Quick: Can you use a single for loop to iterate all elements of a multi-dimensional array? Commit to yes or no.
Common Belief:A single for loop can iterate all elements of a multi-dimensional array.
Tap to reveal reality
Reality:You need nested loops to access each element in multi-dimensional arrays.
Why it matters:Trying a single loop leads to incomplete data access and logic errors.
Quick: Does ignoring the index in a range loop mean you cannot access the element's position? Commit to yes or no.
Common Belief:If you ignore the index in a range loop, you lose the ability to know the element's position.
Tap to reveal reality
Reality:You can choose to ignore the index or value, but if you need the position, you must keep the index variable.
Why it matters:Misunderstanding this causes confusion about how to access element positions during iteration.
Expert Zone
1
Range creates copies of elements, so for large structs, iterating by pointer is more efficient.
2
Modifying the array during iteration by index is safe, but modifying the array length is not possible with arrays (only slices).
3
The order of iteration is guaranteed to be from index 0 to the last index, which is important for deterministic behavior.
When NOT to use
For dynamic collections where size changes, slices or other data structures are better than arrays. Also, for very large data, consider pointer iteration or streaming to avoid copying overhead.
Production Patterns
In real-world Go code, range loops are used extensively for clean, readable iteration. For performance-critical code, developers use pointer iteration or manual loops. Nested loops handle multi-dimensional data like matrices. Ignoring unused variables with underscore is common to keep code clean.
Connections
Slices in Go
Builds-on
Understanding array iteration helps grasp slice iteration since slices are built on arrays but allow dynamic sizing.
Pointers and memory management
Related concept
Knowing how iteration copies values versus using pointers clarifies memory usage and performance in Go.
Assembly language loops
Underlying principle
Iteration in high-level languages like Go abstracts the low-level memory address calculations and jumps done in assembly loops.
Common Pitfalls
#1Trying to modify array elements by changing the value variable in range.
Wrong approach:for _, v := range numbers { v = v * 2 }
Correct approach:for i := range numbers { numbers[i] = numbers[i] * 2 }
Root cause:Misunderstanding that the value variable is a copy, not a reference to the array element.
#2Using a single loop to iterate a multi-dimensional array.
Wrong approach:for i := 0; i < len(matrix); i++ { fmt.Println(matrix[i]) }
Correct approach:for i, row := range matrix { for j, val := range row { fmt.Println(val) } }
Root cause:Not recognizing that multi-dimensional arrays require nested loops to access all elements.
#3Ignoring the index when you actually need it.
Wrong approach:for _, value := range numbers { fmt.Println("Position unknown", value) }
Correct approach:for i, value := range numbers { fmt.Printf("Index %d: %d\n", i, value) }
Root cause:Not planning what information is needed during iteration leads to missing important data.
Key Takeaways
Iterating over arrays means visiting each element one by one to read or change it.
Go provides for loops and the range keyword to make iteration simple and safe.
Range returns copies of elements, so modifying the value variable does not change the original array.
Nested loops are needed for multi-dimensional arrays to access every element.
Understanding how iteration works under the hood helps write efficient and bug-free Go code.

Practice

(1/5)
1. What does the range keyword do when used with an array in Go?
easy
A. It creates a new array with copied elements.
B. It changes the size of the array during iteration.
C. It lets you loop over each element and get its index and value.
D. It sorts the array elements automatically.

Solution

  1. Step 1: Understand the role of range in loops

    The range keyword in Go is used to iterate over elements in arrays, slices, maps, and more, providing both the index and the value of each element.
  2. Step 2: Identify what range does with arrays

    When used with an array, range returns the index and the value of each element one by one, allowing you to process or read each item.
  3. Final Answer:

    It lets you loop over each element and get its index and value. -> Option C
  4. Quick Check:

    range loops with index and value [OK]
Hint: Remember: range gives index and value for each element [OK]
Common Mistakes:
  • Thinking range changes array size
  • Assuming range sorts elements
  • Believing range copies the array
2. Which of the following is the correct syntax to iterate over an array named nums in Go?
easy
A. for i, v := range nums { fmt.Println(i, v) }
B. for i in nums { fmt.Println(i) }
C. foreach i, v in nums { fmt.Println(i, v) }
D. for (i, v) in nums { fmt.Println(i, v) }

Solution

  1. Step 1: Recall Go's for-range loop syntax

    In Go, the correct way to iterate over arrays or slices is using for index, value := range array syntax.
  2. Step 2: Match the syntax with the options

    for i, v := range nums { fmt.Println(i, v) } uses for i, v := range nums, which is the correct Go syntax. Other options use invalid or non-Go syntax.
  3. Final Answer:

    for i, v := range nums { fmt.Println(i, v) } -> Option A
  4. Quick Check:

    Go uses for i, v := range array [OK]
Hint: Use 'for i, v := range array' for Go array loops [OK]
Common Mistakes:
  • Using 'for i in nums' like Python
  • Using 'foreach' which is not Go syntax
  • Using parentheses in for loop header
3. What will be the output of this Go code?
nums := [3]int{10, 20, 30}
for i, v := range nums {
    fmt.Println(i, v)
}
medium
A. 0 0 1 1 2 2
B. 10 0 20 1 30 2
C. Syntax error
D. 0 10 1 20 2 30

Solution

  1. Step 1: Understand the array and loop

    The array nums has 3 elements: 10 at index 0, 20 at index 1, and 30 at index 2. The loop uses range to get index and value.
  2. Step 2: Trace the loop output

    Each iteration prints the index and the value: first line prints "0 10", second "1 20", third "2 30".
  3. Final Answer:

    0 10 1 20 2 30 -> Option D
  4. Quick Check:

    Index and value printed in order [OK]
Hint: range returns index then value in order [OK]
Common Mistakes:
  • Swapping index and value in print
  • Expecting values as indexes
  • Thinking code has syntax error
4. Identify the error in this Go code snippet:
nums := [3]int{1, 2, 3}
for i, v = range nums {
    fmt.Println(i, v)
}
medium
A. Missing colon in 'for i, v = range nums' should be ':='
B. Using '=' instead of '==' in loop condition
C. Array declaration syntax is wrong
D. fmt.Println cannot print two variables

Solution

  1. Step 1: Check the for loop variable declaration

    In Go, when declaring variables in a for-range loop, you must use ':=' to declare and assign variables, not '='.
  2. Step 2: Identify the syntax error

    The code uses '=' instead of ':=' in for i, v = range nums, which causes a syntax error.
  3. Final Answer:

    Missing colon in 'for i, v = range nums' should be ':=' -> Option A
  4. Quick Check:

    Use ':=' to declare variables in for-range loops [OK]
Hint: Use ':=' not '=' in for-range variable declaration [OK]
Common Mistakes:
  • Using '=' instead of ':=' in for loop
  • Confusing assignment with comparison
  • Incorrect array syntax blamed
5. Given an array nums := [5]int{1, 2, 3, 4, 5}, how can you create a new slice containing only the even numbers using iteration?
hard
A. Use a for loop to change the array size and remove odd numbers.
B. Use a for-range loop to check each value and append even numbers to a slice.
C. Use range to multiply all numbers by 2 and store in a new array.
D. Use a for loop with index only and ignore values.

Solution

  1. Step 1: Understand the goal and array

    The goal is to create a new slice with only even numbers from the array nums. Arrays have fixed size, so we cannot remove elements from it.
  2. Step 2: Use for-range loop and append even values

    We iterate over nums using for _, v := range nums, check if v % 2 == 0, and append those values to a new slice.
  3. Final Answer:

    Use a for-range loop to check each value and append even numbers to a slice. -> Option B
  4. Quick Check:

    Filter with for-range and append even numbers [OK]
Hint: Filter with for-range and append to slice [OK]
Common Mistakes:
  • Trying to change array size directly
  • Ignoring values in loop
  • Multiplying instead of filtering
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard