0
0
Goprogramming~15 mins

Iterating over arrays in Go - Deep Dive

Choose your learning style9 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.