04 - Repeating Things

📋 Jump to Takeaways

Imagine printing "Hello" 100 times. You're not going to write 100 Println calls. You need a way to say "do this thing over and over." That's a loop.

The for Loop

Go has one loop keyword: for. That's it. No while, no do...while, no foreach. Just for. It does everything.

The most basic form counts:

for i := 0; i < 5; i++ {
	fmt.Println(i)
}
// 0
// 1
// 2
// 3
// 4

Three parts separated by semicolons:

  1. i := 0 runs once before the loop starts (initialization)
  2. i < 5 is checked before each iteration. If false, the loop stops (condition)
  3. i++ runs after each iteration (i++ means i = i + 1)

Condition-Only Loop

Drop the init and post parts and you get something that works like a while loop in other languages:

count := 0
for count < 3 {
	fmt.Println(count)
	count++
}
// 0
// 1
// 2

This runs as long as the condition is true.

Infinite Loop

Drop everything and the loop runs forever:

for {
	fmt.Println("This never stops")
}

You'll use this pattern when a program should keep running until something specific happens, like a user typing "quit."

break and continue

break exits the loop immediately:

for i := 0; i < 10; i++ {
	if i == 3 {
		break
	}
	fmt.Println(i)
}
// 0
// 1
// 2

continue skips the rest of the current iteration and moves to the next one:

for i := 0; i < 5; i++ {
	if i == 2 {
		continue
	}
	fmt.Println(i)
}
// 0
// 1
// 3
// 4

Looping Through Text

You can loop over the characters in a string with range:

for i, ch := range "Go!" {
	fmt.Printf("index %d: %c\n", i, ch)
}
// index 0: G
// index 1: o
// index 2: !

%c prints a character. If you don't need the index, use _ to ignore it:

for _, ch := range "Go!" {
	fmt.Printf("%c ", ch)
}
// G o !

The _ is Go's way of saying "I know this value exists but I don't need it." The compiler requires you to use every variable you declare. _ is the escape hatch.

Key Takeaways

  • Go has one loop keyword: for
  • for i := 0; i < n; i++ is the counting loop
  • for condition runs while the condition is true
  • for { } runs forever (infinite loop). Use break to exit
  • break exits the loop, continue skips to the next iteration
  • range iterates over strings (and later, slices and maps)
  • _ ignores a value you don't need
  • Loops can be nested, a loop inside a loop

🚀 Ready to run?

Complete runnable examples for this lesson.

📝 Ready to test your knowledge?

Answer the quiz below to mark this lesson complete.

© 2026 ByteLearn.dev. Free courses for developers. · Privacy