Thuta Learning
Go
IntermediateProgrammingBeginner

Loops (For)

GoLesson 1125 min

What you'll walk away with

  • Write three-clause, condition-only and infinite for loops and pick the right one for the job
  • Use range over slices, maps, strings and integers (for i := range n)
  • Use break, continue and a labeled break to leave nested loops
  • Avoid the range-value copy trap and conditions that cause infinite loops

Explain it simply

Explain it simply

A loop says "do this again and again". It is like running laps on a track: you can decide how many laps to run (three), how long to keep going (until you are tired), or have each person on a list run one lap.

Other languages have many keywords for this, such as for, while, do-while and foreach. Go writes all of those shapes with the single word for, so there is less to remember and code reads more uniformly.

Problem → Why → Solution

The problem: a retry loop that never ends

Say you write a loop that tries to connect to a server up to three times. The condition is attempts < 3, but you forget to increase attempts inside the body. The program prints "trying to connect..." forever and pins one CPU core at 100%. The compiler sees nothing wrong, because this is perfectly valid Go.

main.go
package main

import "fmt"

func main() {
	attempts := 0
	for attempts < 3 {
		fmt.Println("trying to connect...")
		// forgot: attempts++
	}
	fmt.Println("gave up") // never reached
}

Why does it never stop?

A for condition { } loop checks its condition before every iteration and keeps going while it is true. If nothing in the body changes the variables in the condition, the condition can never change either. Every loop needs a clear answer to "what makes this stop?": a counter that increases, data that runs out, or a break.

Core concept: one keyword, four shapes

The first shape is the three-clause loop: for i := 1; i <= 3; i++ { }. The init statement (i := 1) runs once, the condition (i <= 3) is checked before every iteration, and the post statement (i++) runs after each one. Go uses no parentheses here, but the braces {} are mandatory. The second shape has only a condition, for balance > 30 { }, which is exactly a while loop in other languages. The third, for { }, has no condition at all and ends only through break or return; it is used for things like a server's main loop.

The fourth shape is the range loop. Over a slice or array, for i, v := range items yields the index and a copy of the element; drop the index with _, or drop the value by writing for i := range items. Over a map it yields keys and values in random order. Over a string it yields the byte index and the rune (Unicode character), so after a multi-byte character such as "é" the index jumps by more than one. Since Go 1.22 you can also range over an integer: in for i := range 3, i takes the values 0, 1 and 2.

break leaves the innermost loop immediately, and continue skips the rest of the current iteration and moves on to the next. With nested loops, break stops only the inner loop; to stop the outer one too, give it a label (search:) and write break search. Since Go 1.22, in modules whose go.mod declares go 1.22 or later, the loop variable is a fresh variable on every iteration, so closures created inside the loop each remember their own i.

Mental model: check, run, advance
  1. Run init once
  2. Check condition; false means exit
  3. Run body (may continue or break)
  4. Post step or next element

Every loop must answer two questions: what moves it forward, and what makes it stop?

General pattern

go
for init; condition; post { body }   // counted loop
for condition { body }                // while-style
for { body; if done { break } }        // infinite until break
for index, value := range collection { body }
for i := range n { body }              // i = 0 .. n-1 (Go 1.22+)

outer:
for ... {
	for ... { if found { break outer } }
}

No parentheses around the condition, and the body always goes in {}. In a range loop discard what you do not need with _, and use a label to leave nested loops.

Example: four loop shapes in one program

This program runs, in order, a three-clause loop counting 1 to 3, a range loop over a slice of names, a while-style loop that subtracts 40 while the balance is above 30, and a range loop over an integer. Work out the final balance before you run it.

main.go
package main

import "fmt"

func main() {
	for i := 1; i <= 3; i++ {
		fmt.Println("count:", i)
	}

	names := []string{"Aung", "Su", "Mya"}
	for _, name := range names {
		fmt.Println("hello", name)
	}

	balance := 100
	for balance > 30 {
		balance -= 40
	}
	fmt.Println("balance:", balance)

	for round := range 2 {
		fmt.Println("round", round)
	}
}

Code breakdown

  1. Three-clausefor i := 1; i <= 3; i++ {

    i starts at 1 and 3 is included, so three lines print: count: 1, 2 and 3. i exists only inside the loop.

  2. Range, value onlyfor _, name := range names {

    The index is discarded with _ and name is a copy of each element. Slices keep their order, so hello Aung, Su and Mya print in sequence.

  3. While-stylefor balance > 30 {

    100 becomes 60, then 20; 20 > 30 is false, so it stops. balance -= 40 changes the variable in the condition, which is what lets the loop end.

  4. Range over intfor round := range 2 {

    Since Go 1.22 you can range over an integer. round takes 0 and 1; 2 itself is excluded.

You should see
count: 1
count: 2
count: 3
hello Aung
hello Su
hello Mya
balance: 20
round 0
round 1
Execution flow of a three-clause loop
  1. Init: i := 1
  2. Condition: i <= 3 ?
  3. Run the body
  4. Post: i++, then re-check the condition

Condition true

run body -> i++ -> check again

Condition false

leave the loop, continue after it

String range, loop variables and the range-value copy

This snippet shows three things. Ranging over "héllo" skips index 2 and jumps to 3, because é takes two UTF-8 bytes. The three closures print 0 1 2 because each iteration has its own i; before Go 1.22 the same code printed 3 3 3. Finally, editing the range value n leaves the slice untouched, while editing nums[i] really changes it.

range_details.go
package main

import "fmt"

func main() {
	for i, r := range "héllo" {
		fmt.Print(i, ":", string(r), " ") // 0:h 1:é 3:l 4:l 5:o
	}
	fmt.Println()

	var printers []func()
	for i := 0; i < 3; i++ {
		printers = append(printers, func() { fmt.Print(i, " ") })
	}
	for _, p := range printers {
		p() // 0 1 2 (each iteration has its own i)
	}
	fmt.Println()

	nums := []int{1, 2, 3}
	for _, n := range nums {
		n *= 10 // changes a copy only
	}
	fmt.Println(nums) // [1 2 3]
	for i := range nums {
		nums[i] *= 10
	}
	fmt.Println(nums) // [10 20 30]
}

In real projects

Where this shows up in real projects

The range loop is the most common loop in Go code: totalling orders, filtering a user list, and so on. Reading a file line by line with bufio.Scanner looks like for scanner.Scan() { }, and walking database results looks like for rows.Next() { }. Those last two are condition-only loops that stop when the method returns false because the data has run out.

Infinite for { } loops are used on purpose too: a worker that waits for jobs from a queue, or a server loop accepting network connections. Such loops need a carefully designed way to stop, such as a shutdown signal or a cancelled context, which the concurrency lessons cover with select and context. For retry logic, a bounded loop like for attempt := range 3 with a short pause between attempts keeps a struggling server from being hammered by retries.

Common mistakes

Common mistakes

1. Never changing the condition's variable

Forget attempts++, as in the problem section's retry loop, and the loop never ends while burning a full CPU core. Writing retries as for attempt := range 3 lets Go advance the counter for you, so there is nothing to forget.

2. Editing the range value instead of the element

for _, n := range nums { n *= 10 } changes only a copy, so nums is unchanged. It is even sneakier with structs: for _, u := range users { u.Active = true } activates nobody. Write users[i].Active = true using the index.

3. Expecting break to leave every loop

Calling break when you find an answer in a nested loop stops only the inner loop; the outer one keeps going, often printing several answers or doing extra work. Use a label with break outer, or move the loops into a function and return.

Best practices

Best practices

  • Prefer range when walking a collection; it leaves less room for index and off-by-one bugs.
  • To repeat something count times on Go 1.22+, write for i := range count, and keep the three-clause loop for cases where you steer the index yourself.
  • When a loop body grows long, extract it into a function; a return often reads more clearly than a label.

Mini challenge

Mini challenge: daily order checks

Use three loop shapes to solve three shop tasks: totalling orders, finding two items that fit a budget, and doubling savings.

  • Total the amounts, skipping negative refunds with continue and stopping at 0 with break
  • Find the first pair in prices that adds up to a budget of 65 with nested loops, leaving them with a labeled break
  • Double savings, starting from 100, until it reaches 1000 or more, counting the months
  • Print "no pair" when no pair is found
orders.go
package main

import "fmt"

func main() {
	amounts := []int{120, -20, 300, 0, 50}
	total := 0
	// TODO: range over amounts; break at 0, continue on negatives
	fmt.Println("total:", total)

	prices := []int{15, 40, 25, 60}
	budget := 65
	// TODO: label the outer loop, compare every pair i < j,
	// print "pair:" and break out of both loops when they sum to budget
	_, _ = prices, budget

	savings, months := 100, 0
	// TODO: while savings < 1000, double it and count months
	fmt.Println("months:", months, "savings:", savings)
}

Expected: total: 420 pair: 40 25 months: 4 savings: 1600

Show hint

0 is not negative, so the order of the two ifs does not change the result here, but putting the stop condition first reads more clearly. Write the label on its own line before the outer for, as in search:, and start the inner loop at j := i + 1 so no pair is checked twice.

Show solution
orders.go
package main

import "fmt"

func main() {
	amounts := []int{120, -20, 300, 0, 50}
	total := 0
	for _, amount := range amounts {
		if amount == 0 {
			break
		}
		if amount < 0 {
			continue
		}
		total += amount
	}
	fmt.Println("total:", total)

	prices := []int{15, 40, 25, 60}
	budget := 65
	found := false
search:
	for i := range prices {
		for j := i + 1; j < len(prices); j++ {
			if prices[i]+prices[j] == budget {
				fmt.Println("pair:", prices[i], prices[j])
				found = true
				break search
			}
		}
	}
	if !found {
		fmt.Println("no pair")
	}

	savings, months := 100, 0
	for savings < 1000 {
		savings *= 2
		months++
	}
	fmt.Println("months:", months, "savings:", savings)
}

Quick quiz 1 / 3

What does for i := range 3 { fmt.Print(i) } print?

Quick quiz 2 / 3

In for i, r := range "héllo", what is i for the first "l"?

Quick quiz 3 / 3

What does a plain break (no label) inside the inner loop of a nested loop do?

What to remember

  • Go's single for keyword covers three-clause, while-style, infinite and range loops.
  • range yields index and copy for slices, random order for maps, byte index and rune for strings, and 0..n-1 for integers.
  • break, continue and labeled break control the flow, and every loop needs a clear way to stop.
  • To change elements, assign to s[i], not the range value; since Go 1.22 each iteration gets a fresh loop variable.

A Tour of Go — Go

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Loops (For) | Thuta Learning