Introduction

Loops are essential for repetitive tasks in programming. In Go, the for loop is used for iterating through elements, and the range keyword simplifies working with slices, arrays, and maps. In this guide, we'll explore both loop structures with sample code and explanations.


The for Loop

The for loop is a fundamental control structure in Go. It allows you to repeatedly execute a block of code as long as a condition is true. Here's an example:

                            package main
import "fmt"
func main() {
for i := 0; i < 5; i++ {
fmt.Println("Iteration:", i)
}
}

In this code, the for loop runs as long as the condition i < 5 is true. It prints the value of i in each iteration.


The range Loop

The range keyword simplifies iterating through elements in slices, arrays, and maps. Here's an example of using the range loop with a slice:

                            package main
import "fmt"
func main() {
fruits := []string{"apple", "banana", "cherry"}
for index, fruit := range fruits {
fmt.Printf("Index: %d, Fruit: %s\n", index, fruit)
}
}

In this code, the range loop iterates through the elements of the fruits slice, providing both the index and the value in each iteration.


Infinite Loops

You can create an infinite loop using the for loop. Be cautious when using infinite loops, as they can lead to your program running indefinitely. Here's an example:

                            package main
import "fmt"
func main() {
for {
fmt.Println("This is an infinite loop!")
}
}

An infinite loop runs continuously until interrupted manually.


Further Resources

To continue exploring loops in Go, consider these resources: