Coding/Learn/go/go loops and flow control
Go Foundational Course
01.Introduction, Toolchain & Package main
02.Variables, Zero Values, Constants & iota
03.Control Flow: If with Init Statements & Switch
04.The Unified For Loop & Range Iteration
05.Functions, Multiple Return Values & Named Returns
06.Arrays vs Slices: Dynamic Memory & Headers
07.Maps: Key-Value Hash Tables & Safe Access
08.Pointers & Value vs Pointer Semantics
09.Structs, Receiver Methods & Composition
10.Implicit Interfaces & Duck Typing with Typesafety
11.Explicit Error Handling, Wrapping & Inspection
12.Defer, Panic & Recover: Resource Cleanup
13.Strings, Runes & UTF-8 Encoding Internals
14.Goroutines & The M:N Work-Stealing Scheduler
15.Channels: CSP Concurrency & Pipelines
16.Select Statement, Non-Blocking IO & Timeouts
17.Mutexes, RWMutex & Atomic Primitives
18.Context Propagation, Cancellation & Deadlines
19.JSON Serialization, Tags & net/http Routing
20.Capstone: High-Performance Concurrent Microservice Engine
Course Certificate0%

Complete all lessons to earn

LearnThe Unified For Loop & Range Iteration
4 / 20 0%
Lesson 04 of 20
6 mins read

The Unified For Loop & Range Iteration

PreviousNext Lesson
In Plain English

Go simplifies iteration by having only one loop keyword: for. It unifies 4 patterns: traditional 3-component index loops, condition-only while loops, infinite loops (for {}), and range loops over slices, maps, strings, and channels.

The Mental Model

"The Go for loop is a Swiss Army knife that replaces while, do-while, and foreach with a single versatile blade."

Deep Dive: How It Works

3-Component Loop: for i := 0; i < n; i++ { ... }

While Equivalent: for condition { ... }

Range Iteration: for index, value := range slice { ... }

Syntax Blueprint

for i := 0; i < 5; i++ {
    fmt.Println(i)
}

for idx, item := range items {
    fmt.Printf("%d: %s\n", idx, item)
}

Index iteration and collection range traversal using the for keyword.

PointCore Rules to Remember

Point star
Single Loop Keyword: No while or do-while keywords exist in Go—for handles every iteration pattern.
Point star
Range Value Copy: range returns a copy of each element; use index slice[i] to mutate in-place.
Point star
Blank Identifier: Ignore indices with for _, val := range items if index position is unneeded.

Common Beginner Traps & How to Fix Them

Mistake:Taking the memory address of the range iteration value pointer: &val.

Why it happens: In older Go versions, val was a single shared variable reused across iterations.

How to fix: Index the slice directly: &items[i].

Pro Tip: Use for key := range myMap when you only care about map keys without reading payload values.

Live Interactive Example

Hit Run Code to see it live
Range Over Slice Elements
Go 1.22 / Runtime
1
2
3
4
5
6
7
8
9
10
11
Output Console
Click "Run Code" to view the rendered output.
How it works: range returns 0-based index and element string copy for each item in the slice.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Calculate Sum of Squares with For Loop

  • PointCalculate the sum of squares for integers 1 through 4 (1^2 + 2^2 + 3^2 + 4^2 = 30).
  • PointPrint "Sum of Squares: %d\n" with total sum.
1
2
3
4
5
6
7
8
9
10
11
12
13
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates