Go For Loops:
In Go, the for loop is the only looping construct, but it can be used in a variety of ways to achieve the functionality of while, foreach, and infinite loops.
Basic For Loop
This is the standard form, similar to C-style for loops:
go
package main
import "fmt"
func main() {
for i := 1; i <= 5; i++ {
fmt.Println(i)
}
}While-Style Loop
Omit the init and post statements to create a loop similar to while.
go
package main
import "fmt"
func main() {
i := 1
for i <= 5 {
fmt.Println(i)
i++
}
}Infinite Loop
Use for without a condition to create an infinite loop.
go
package main
import "fmt"
func main() {
count := 0
for {
fmt.Println("Looping...")
count++
if count == 3 {
break
}
}
}For Range Loop
Used to iterate over slices, arrays, maps, and strings.
go
package main
import "fmt"
func main() {
numbers := []int{1, 2, 3, 4}
for index, value := range numbers {
fmt.Printf("Index: %d, Value: %d\n", index, value)
}
}