Is there a foreach construct in the Go language?

In Go, there is no foreach keyword or construct like you might find in some other programming languages (e.g., PHP, JavaScript). Instead, Go uses the for loop in a slightly different way to iterate over elements of various data structures, including arrays, slices, strings, maps, and channels.

The for loop in Go can be used in three different ways to achieve iteration:

  1. Basic for Loop: The basic for loop is similar to traditional for loops in other languages. It is used to loop over elements of arrays, slices, and strings.

Example:

package main

import "fmt"

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

    for i := 0; i < len(numbers); i++ {
        fmt.Println(numbers[i])
    }
}
  1. Range-based for Loop: The range-based for loop is used to iterate over elements of arrays, slices, strings, and maps. It provides a more concise and readable way to perform iteration.

Example:

package main

import "fmt"

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

    for _, num := range numbers {
        fmt.Println(num)
    }
}
  1. for Loop with Channels: The for loop can be used to read values from a channel. When reading from a channel, the loop continues until the channel is closed.

Example:

package main

import "fmt"

func main() {
    ch := make(chan int)

    go func() {
        for i := 1; i <= 5; i++ {
            ch <- i
        }
        close(ch)
    }()

    for receivedValue := range ch {
        fmt.Println(receivedValue)
    }
}

In this example, the for range loop reads values from the channel ch until the channel is closed. The loop will exit automatically when there are no more values to receive.

Although Go doesn’t have a foreach keyword, the combination of the for loop and range-based iteration makes it easy to iterate over elements of various data structures in a clear and concise manner. The range keyword is especially useful for iterating over collections and channels, as it abstracts away the index manipulation and provides an intuitive way to loop over elements directly.

error: Content is protected !!