0
0
Goprogramming~15 mins

For loop basics in Go - Deep Dive

Choose your learning style9 modes available
Overview - For loop basics
What is it?
A for loop in Go is a way to repeat a set of instructions multiple times. It helps you run the same code again and again until a condition is met. This is useful when you want to process items in a list or count numbers. The for loop is the only looping construct in Go, making it simple and powerful.
Why it matters
Without loops, you would have to write the same code many times to do repetitive tasks, which is slow and error-prone. For loops let you automate repetition, saving time and reducing mistakes. They are essential for tasks like processing data, running timers, or handling user input repeatedly.
Where it fits
Before learning for loops, you should understand basic Go syntax and variables. After mastering for loops, you can learn about arrays, slices, and more complex control flows like nested loops and concurrency patterns.
Mental Model
Core Idea
A for loop repeats a block of code while a condition is true or for a set number of times.
Think of it like...
A for loop is like a music playlist that plays songs one after another until it reaches the end or you stop it.
┌───────────────┐
│ Initialize    │
├───────────────┤
│ Check Condition ──┐
├───────────────┤  │
│ Execute Body   │  │
├───────────────┤  │
│ Update Step   ◄──┘
└───────────────┘
Build-Up - 6 Steps
1
FoundationBasic for loop syntax
🤔
Concept: Learn the structure of a simple for loop with initialization, condition, and update.
In Go, a basic for loop looks like this: for i := 0; i < 5; i++ { // code to repeat fmt.Println(i) } - i := 0 sets the start value. - i < 5 is the condition to keep looping. - i++ increases i by 1 each time. This prints numbers 0 to 4.
Result
0 1 2 3 4
Understanding the three parts of the for loop helps you control exactly how many times the code runs.
2
FoundationLooping with condition only
🤔
Concept: Use a for loop with only a condition, like a while loop.
Go allows a for loop with just a condition: count := 0 for count < 3 { fmt.Println(count) count++ } This repeats as long as count is less than 3.
Result
0 1 2
Knowing that for loops can act like while loops gives you flexibility in how you write loops.
3
IntermediateInfinite loops with for
🤔Before reading on: do you think a for loop without any condition stops on its own? Commit to yes or no.
Concept: A for loop with no condition runs forever unless stopped inside the loop.
An infinite loop looks like this: for { fmt.Println("Looping forever") break // stops the loop } Without break, this would run endlessly.
Result
Looping forever
Recognizing infinite loops helps prevent programs that freeze or crash by running endlessly.
4
IntermediateUsing for with range
🤔Before reading on: do you think for loops can directly loop over collections like arrays? Commit to yes or no.
Concept: The for range loop lets you iterate over elements in arrays, slices, maps, or strings easily.
Example looping over a slice: nums := []int{10, 20, 30} for index, value := range nums { fmt.Println(index, value) } This prints each index and value in the slice.
Result
0 10 1 20 2 30
Using for range simplifies looping over collections without manual index management.
5
AdvancedModifying loop variables safely
🤔Before reading on: do you think changing the loop variable inside the loop affects the next iteration? Commit to yes or no.
Concept: Changing the loop variable inside the loop body does not affect the loop's control variable in the next iteration.
Example: for i := 0; i < 3; i++ { fmt.Println(i) i = 10 // changing i inside loop } Output is still 0, 1, 2 because the loop increments i after each iteration.
Result
0 1 2
Understanding loop variable behavior prevents bugs where changing variables inside loops doesn't do what you expect.
6
ExpertLoop variable scope and closures
🤔Before reading on: do you think loop variables keep the same value inside closures created in the loop? Commit to yes or no.
Concept: Loop variables are reused in each iteration, which can cause unexpected behavior when used inside closures like goroutines.
Example: for i := 0; i < 3; i++ { go func() { fmt.Println(i) }() } This may print 3,3,3 instead of 0,1,2 because the closure captures the variable, not its value. Fix by passing i as a parameter: for i := 0; i < 3; i++ { go func(n int) { fmt.Println(n) }(i) }
Result
0 1 2 (order may vary)
Knowing how closures capture variables avoids subtle concurrency bugs in Go programs.
Under the Hood
The Go compiler translates the for loop into a control flow that initializes variables, checks the condition before each iteration, executes the loop body, and updates variables. The loop variable is stored in memory and updated each cycle. For range loops use iterators internally to access collection elements one by one.
Why designed this way?
Go uses a single for loop construct to keep the language simple and consistent. This design avoids confusion from multiple loop types and makes the language easier to learn and maintain. The range form was added to simplify common iteration patterns over collections.
┌───────────────┐
│ Initialization│
└──────┬────────┘
       │
┌──────▼───────┐
│ Condition?   │
├──────┬───────┤
│ Yes  │ No    │
│      ▼       │
│  Execute Body│
│      │       │
│  Update Vars │
└──────┴───────┘
       │
       └─────▶ (loop back to Condition)
Myth Busters - 3 Common Misconceptions
Quick: Does changing the loop variable inside the loop body affect the next iteration? Commit to yes or no.
Common Belief:If I change the loop variable inside the loop, the next iteration uses the new value.
Tap to reveal reality
Reality:The loop variable is updated by the loop control after each iteration, so changes inside the loop body do not affect the next iteration's value.
Why it matters:Assuming changes affect the loop can cause infinite loops or skipped iterations, leading to bugs.
Quick: Does a for loop without a condition stop automatically? Commit to yes or no.
Common Belief:A for loop without a condition will stop after some time or iterations.
Tap to reveal reality
Reality:A for loop with no condition runs forever unless explicitly stopped with break or return.
Why it matters:Not knowing this can cause programs to freeze or crash due to infinite loops.
Quick: When using for range with closures, do closures capture the current loop value or the variable itself? Commit to your answer.
Common Belief:Closures capture the current value of the loop variable in each iteration.
Tap to reveal reality
Reality:Closures capture the loop variable itself, which is reused, causing all closures to see the final value after the loop ends.
Why it matters:This causes unexpected behavior in concurrent code, leading to hard-to-find bugs.
Expert Zone
1
The loop variable in for range is reused each iteration, so taking its address inside the loop requires care.
2
For loops can be optimized by the compiler to reduce overhead, especially when the number of iterations is known at compile time.
3
Using break and continue inside nested loops affects only the innermost loop, which can confuse beginners.
When NOT to use
For extremely large or infinite data streams, using channels with goroutines or specialized iterator patterns is better than simple for loops. Also, recursion or functional programming patterns may be preferred for some problems.
Production Patterns
In real-world Go code, for loops are often combined with range to process slices and maps. They are used in server loops, reading files line by line, and controlling concurrency with goroutines and channels.
Connections
Recursion
Alternative approach to repetition
Understanding for loops helps grasp recursion as another way to repeat tasks, but recursion uses function calls instead of explicit loops.
Event loops in JavaScript
Both manage repeated tasks but in different environments
Knowing how for loops work clarifies how event loops schedule repeated or delayed actions in asynchronous programming.
Assembly language loops
Low-level implementation of loops
Seeing for loops in Go connects to how loops are built from jump instructions in assembly, deepening understanding of program flow.
Common Pitfalls
#1Infinite loop by missing update step
Wrong approach:for i := 0; i < 5; { fmt.Println(i) }
Correct approach:for i := 0; i < 5; i++ { fmt.Println(i) }
Root cause:Forgetting to update the loop variable causes the condition to never become false, making the loop run forever.
#2Using loop variable address inside for range incorrectly
Wrong approach:for _, v := range slice { go func() { fmt.Println(&v) }() }
Correct approach:for _, v := range slice { vCopy := v go func() { fmt.Println(&vCopy) }() }
Root cause:The loop variable is reused each iteration, so closures capturing its address see the same memory location.
#3Assuming for loop with condition only runs once
Wrong approach:count := 0 for count < 3 { fmt.Println(count) }
Correct approach:count := 0 for count < 3 { fmt.Println(count) count++ }
Root cause:Not updating the condition variable inside the loop causes an infinite loop.
Key Takeaways
The for loop in Go is a versatile tool that repeats code while a condition holds or for a set number of times.
It has three parts: initialization, condition, and update, but can also be used with just a condition or no condition for infinite loops.
The for range form simplifies looping over collections like slices and maps without manual indexing.
Loop variables behave in specific ways inside loops and closures, which can cause subtle bugs if misunderstood.
Mastering for loops is essential for writing efficient, clear, and correct Go programs.