Go - For Loop
Beginner 10/10
Teacher 10/10
Architect 10/10
Forms
for i := 0; i < 3; i++ { fmt.Println(i) }
for i < 10 { i++ } // while-like
for i, v := range []string{"a","b"} { fmt.Println(i, v) }
Common errors
- Mutating a slice while iterating over it with
range
—collect changes first. - Forgetting to update the loop variable in while-like forms.
Practice
- Sum only the even numbers in a slice of ints using
range
.
Quick quiz
- What are the three forms of
for
in Go?
Show answer
Classicfor init; cond; post
, while-like for cond
, and infinite for
.