for
Go has only one looping construct: for. It covers C-style three-part loops, condition-only loops (like while), infinite loops, and range-based iteration — all with a single keyword.
Syntax
// Three-part form (init; condition; post)
for i := 0; i < 10; i++ {
}
// Condition only (equivalent to while)
for condition {
}
// Infinite loop
for {
}
// Range-based iteration
for i, v := range slice {
}
for k, v := range mapVar {
}
for i, r := range str { // i = byte position, r = rune value
}
// Index or value only
for i := range slice { // index only
}
for _, v := range slice { // value only (discard index with _)
}
Syntax overview
| Syntax | Description |
|---|---|
| for i := 0; i < n; i++ { } | C-style three-part for loop. Combines initialization, condition, and post statement on one line. |
| for condition { } | Equivalent to a while loop in other languages. Loops as long as the condition is true. |
| for { } | Infinite loop. Use break or return to exit. |
| for i, v := range s { } | Iterates over a slice, array, map, string, or channel. |
| break | Exits the loop immediately. Can be combined with a label to break out of an outer loop. |
| continue | Skips the rest of the current iteration and moves to the next one. |
Sample code
package main
import "fmt"
func main() {
// Three-part form
sum := 0
for i := 1; i <= 5; i++ {
sum += i
}
fmt.Println("Sum:", sum) // 15
// Iterate over a slice with range
fruits := []string{"apple", "orange", "grape"}
for i, v := range fruits {
fmt.Printf("%d: %s\n", i, v)
}
// Iterate over a map with range
scores := map[string]int{"Alice": 85, "Bob": 92}
for name, score := range scores {
fmt.Printf("%s: %d\n", name, score)
}
// Skip with continue (print even numbers only)
for i := 0; i < 10; i++ {
if i%2 != 0 {
continue
}
fmt.Print(i, " ")
}
fmt.Println()
// Use a labeled break to exit an outer loop all at once
outer:
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
if i == 1 && j == 1 {
break outer
}
fmt.Printf("(%d,%d) ", i, j)
}
}
fmt.Println()
}
Notes
Range-based loops work with slices, arrays, maps, strings, and channels. When used on a string, range yields byte positions and rune values as pairs, so multi-byte characters such as CJK text are handled correctly one character at a time.
Values returned by range are copies. You cannot modify slice elements directly through a range loop. To modify elements, access them by index: for i := range s { s[i] = ... }.
Labeled break and continue use the same mechanism as labels. They are useful for breaking out of deeply nested loops at once, but overuse can make code harder to read.
If you find any errors or copyright issues, please contact us.