For-Range loop in golang

The for-range loop in Go is used to iterate over elements of an array, slice, string, map, or channel. Here's an explanation of each step involved in a for-range loop:

  1. Initialize the loop: The for-range loop starts by declaring two variables, one for the index and one for the value of each element in the collection being iterated.

  2. Iterate over the collection: The loop iterates over each element in the collection. It automatically assigns the index and value of the current element to the variables declared in the initialization step.

  3. Execute the loop body: The loop body contains the code that will be executed for each element in the collection. You can perform any desired operations on the current element using the assigned variables.

  4. Repeat until the collection is exhausted: The loop continues to iterate over the collection until all elements have been processed.

Here's an example of a for-range loop in Go:

package main

import "fmt"

func main() {
    numbers := []int{1, 2, 3, 4, 5}

    for index, value := range numbers {
        fmt.Printf("Index: %d, Value: %d\n", index, value)
    }
}

In this example, we have an integer slice called numbers. The for-range loop iterates over each element in the numbers slice, assigning the index to the index variable and the corresponding value to the value variable. The loop body then prints the index and value of each element.

The output of this program will be:

Index: 0, Value: 1
Index: 1, Value: 2
Index: 2, Value: 3
Index: 3, Value: 4
Index: 4, Value: 5

This demonstrates how the for-range loop can be used to easily iterate over elements in a collection in Go.