04 - Repeating Things
📋 Jump to TakeawaysImagine 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
// 4Three parts separated by semicolons:
i := 0runs once before the loop starts (initialization)i < 5is checked before each iteration. If false, the loop stops (condition)i++runs after each iteration (i++meansi = 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
// 2This 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
// 2continue 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
// 4Looping 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 loopfor conditionruns while the condition is truefor { }runs forever (infinite loop). Usebreakto exitbreakexits the loop,continueskips to the next iterationrangeiterates over strings (and later, slices and maps)_ignores a value you don't need- Loops can be nested, a loop inside a loop