Loops
Examples
Filter
for is Go’s only looping construct. Here are three basic types of for loops.
package main
import "fmt"
func main() {
i := 1
for i <= 3 {
fmt.Println(i)
i = i + 1
}
for j := 7; j <= 9; j++ {
fmt.Println(j)
}
for {
fmt.Println("loop")
break
}
for n := 0; n <= 5; n++ {
if n%2 == 0 {
continue
}
fmt.Println(n)
}
}
// V has only one looping construct: for.
numbers := [1, 2, 3, 4, 5]
for num in numbers {
println(num)
}
names := ['Sam', 'Peter']
for i, name in names {
println('$i) $name') // Output: 0) Sam
} // 1) Peter
// The for value in loop is used for going through elements of an array. If an index is required, an alternative form for index, value in can be used.
// Note, that the value is read-only. If you need to modify the array while looping, you have to use indexing:
mut numbers2 := [1, 2, 3, 4, 5]
for i, num in numbers2 {
println(num)
numbers2[i] = 0
}
// This form of the loop is similar to while loops in other languages.
// The loop will stop iterating once the boolean condition evaluates to false.
// Again, there are no parentheses surrounding the condition, and the braces are always required.
mut sum := 0
mut i := 0
for i <= 100 {
sum += i
i++
}
println(sum) // "5050"
// The condition can be omitted, this results in an infinite loop.
mut num := 0
for {
num++
if num >= 10 {
break
}
}
println(num) // "10"
// Finally, there's the traditional C style for loop. It's safer than the `while` form because with the latter it's easy to forget to update the counter and get stuck in an infinite loop.
// Here i doesn't need to be declared with mut since it's always going to be mutable by definition.
for i := 0; i < 10; i++ {
// Don't print 6
if i == 6 {
continue
}
println(i)
}