For-loop. The Go language has a single loop: the for-loop. But this loop can be used in many ways, to loop from a start to an end, or until a condition is reached.
With range, a keyword, we can iterate over more complex things like slices or maps. Range, used with for, helps us manage iteration.
Example. This code uses the classic for-loop where we begin at a certain number and end at another. After each body evaluation, the index is incremented (1 is added to it).
Start The variable "i" is declared and initialized to 0. The ":=" syntax indicates that this is a new variable.
Info We separate the 3 clauses of this form of the for-loop with semicolons. Braces are used for the loop body.
package main
import "fmt"
func main() {
// Loop from 0 until 5 is reached.
for i := 0; i < 5; i++ {
// Display integer.
fmt.Println(i)
}
}0
1
2
3
4
No conditions. A for-loop can be specified with no condition. This loop continues infinitely until broken (as by a return or break statement).
Tip This is the same as a "while true" loop in other languages. It is a loop that has no specified terminating condition.
package main
import "fmt"
func main() {
id := 10
// This loop continues infinitely until broken.
for {
// Break if id is past a certain number.
if id > 20 {
break
}
fmt.Println(id)
id += 5
}
}10
15
20
Runes, string. It is possible to use a for-range loop to iterate over the runes (characters) in a string. Each rune may contain more than one byte, but only one Unicode code point.
package main
import "fmt"
func main() {
// Loop over runes in a string.
word := "cat"
for i, letter := range word {
fmt.Println(i, "=", letter)
}
}0 = 99
1 = 97
2 = 116
Condition, while. There is no while keyword here, but the for-loop can be used as a while-loop. It continues while the condition specified after "for" is true.
Here The variables "valid" and "i" are initialized. While "valid" is true, the loop continues iterating.
Finally The loop terminates after the variable "i" is incremented to 3, and valid is set to false.
package main
import "fmt"
func main() {
valid := true
i := 0
// This loop continues while "valid" is true.
for valid {
// If i equals 3, set "valid" to false.
if i == 3 {
valid = false
}
fmt.Println(i)
i++
}
}0
1
2
3
Range and slice. The range keyword is used with a for-loop. When we use range on a slice, all the indexes in the slice are enumerated.
So The range of the three-element int slice here returns 0, 1 and 2. We use those to get elements from the slice.
package main
import "fmt"
func main() {
// Create a slice of three ints.
ids := []int{10, 21, 35}
// Loop over range of indexes in the slice.
for i := range ids {
fmt.Println(ids[i])
}
}10
21
35
Range, no variables. Suppose we want to repeat a loop once for each element in a slice, but the loop does not use the slice. We can omit all the variables in a for-range loop.
Here We repeat a loop 3 times, based on the number of cats in the cats slice. We just print a message each time.
package main
import "fmt"
func main() {
cats := []string{"Spot", "Meow", "Mittens"}
// Use a range loop with no variables.
for range cats {
fmt.Println("CAT ITERATION")
}
}CAT ITERATION
CAT ITERATION
CAT ITERATION
Foreach loop. Go does not have a foreach keyword. But we can use a foreach loop by receiving 2 values in a for-range loop. We ignore the first, and the second is each element's value.
package main
import "fmt"
func main() {
// Two strings in a slice.
animals := []string{"bird", "frog"}
// Loop over each element directly (foreach loop).// ... Ignore the first pair of each returned pair (the index).
for _, animal := range animals {
fmt.Println(animal)
}
}bird
frog
Decrement. A loop can decrement from a higher number to a lower one. We often test for "greater than or equal to" 0 in this case. The decrement statement uses two minus signs.
package main
import "fmt"
func main() {
// Decrement loop.
for i := 4; i >= 0; i-- {
// Display loop index.
fmt.Println(i)
}
}4
3
2
1
0
Summary. The for-loop in Go has many purposes. We use one of its forms to iterate in many ways. With range, a helpful keyword, we iterate in a clear way over collections.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 29, 2025 (edit).