1
0
Fork 0
pr3-sose2026-fork/go/01-basics/03-for.go

43 lines
905 B
Go

package main
import "fmt"
func main() {
// For is the only loop statement in Go. No parentheses are needed around the condition,
// but the curly braces are required.
i := 1
// The most basic type, with a single condition.
for i <= 3 {
fmt.Println(i)
i = i + 1
}
// Like in C, the first and third components of the for statement are optional.
for j := 0; j < 3; j++ {
fmt.Println(j)
}
// The range form of the for loop iterates over a slice or map.
for i := range 3 {
fmt.Println("range", i)
}
// Infinite loops are formed by omitting the loop condition; the loop will repeat
// until you break out of it or return from the enclosing function.
for {
fmt.Println("loop")
break
}
// The range form of the for loop can also be used with arrays, slices, maps, and strings.
for n := range 6 {
if n%2 == 0 {
// Skip even numbers.
continue
}
fmt.Println(n)
}
}