The For Loop
Most languages give you a toolbox of loops: while, do-while, for,
sometimes loop or repeat. Go gives you one keyword — for — and lets it
take a few shapes. One keyword means one thing to learn, one thing to read,
and no debates about which loop to use.
The classic three-part form
This is the for you may know from other languages: an init statement, a
condition, and a post statement, separated by semicolons — and, like if,
with no parentheses around them:
package main
import "fmt"
func main() {
for i := 1; i <= 5; i++ {
fmt.Println(i)
}
}
i := 1 runs once before the loop; i <= 5 is checked before every
iteration; i++ runs after each one. The variable i exists only inside the
loop — a small scope is a safe scope.
Drop the semicolons and it's a while
Leave out the init and post statements and for becomes what other languages
call while: keep looping as long as the condition holds.
package main
import "fmt"
func main() {
n := 1
for n < 100 {
n *= 2
}
fmt.Println(n) // 128
}
Same keyword, same braces — just less punctuation.
Drop everything and it loops forever
for with no condition at all loops until something stops it. Pair it with
break, which exits the loop immediately:
package main
import "fmt"
func main() {
countdown := 3
for {
fmt.Println(countdown)
countdown--
if countdown == 0 {
break
}
}
fmt.Println("Liftoff!")
}
Infinite loops sound alarming, but they're idiomatic Go — servers, for
example, are essentially a for {} that accepts one request per iteration.
continue skips to the next round
Where break leaves the loop, continue abandons the current iteration and
jumps straight to the next one:
package main
import "fmt"
func main() {
for i := 1; i <= 10; i++ {
if i%2 != 0 {
continue // odd — skip it
}
fmt.Println(i) // prints 2, 4, 6, 8, 10
}
}
Used near the top of a loop body, continue filters out the cases you don't
care about, so the interesting code below it stays unindented.
A preview: for range
There is one more shape — for i, v := range collection — which walks over
slices, maps, strings, and more. It's the loop you'll eventually use most,
but it belongs with the collections that feed it, so we'll cover it properly
in the chapter on slices and maps. For counting and conditions, the forms
above are all you need.
The exercise below asks you to put a loop to work: summing the numbers from 1
to n.
Practice
1. Sum to N
BeginnerImplement
sumToNso it returns the sum of every integer from 1 up to and includingn— that is,1 + 2 + ... + n.func sumToN(n int) intFor example,
sumToN(5)is1 + 2 + 3 + 4 + 5 = 15.If
nis0or negative, there is nothing to add, so return0.Use a
forloop to build the sum — this exercise is about loops, so resist the temptation to reach for the closed-formn*(n+1)/2formula.package main import "fmt" // sumToN returns 1 + 2 + ... + n, or 0 when n is zero or negative. func sumToN(n int) int { // TODO: implement return 0 } func main() { fmt.Println(sumToN(5)) }Sign in to write and run your solution in the browser.
Sign in for hints and the solution.