Monday, January 20, 2025
HomeProgrammingIs There A Foreach Loop In Go?

Is There A Foreach Loop In Go?

Go does not have a built-in foreach loop like some other languages (e.g., JavaScript or PHP). However, you can achieve similar functionality using Go’s for loop with the range keyword.

The range keyword is used to iterate over elements in various data structures like arrays, slices, maps, and strings. Here’s how you can use it to loop through collections in a way that mimics a foreach loop.

See also  SQL LEFT JOIN

Example for looping over a slice:

package main

import "fmt"

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

    // Using for-range to iterate over the slice
    for _, num := range numbers {
        fmt.Println(num)
    }
}
  • range returns two values: the index (_ is used to ignore it) and the value of the element.
  • You can omit the index if you don’t need it by using an underscore (_).
See also  Is there a shorter way to write a for loop in Java?

Example for looping over a map:

package main

import "fmt"

func main() {
    personAge := map[string]int{"Alice": 25, "Bob": 30, "Charlie": 35}

    // Using for-range to iterate over the map
    for name, age := range personAge {
        fmt.Printf("%s is %d years old\n", name, age)
    }
}

Example for looping over a string:

package main

import "fmt"

func main() {
    str := "Hello"

    // Using for-range to iterate over the string (each character is returned as a rune)
    for _, char := range str {
        fmt.Printf("%c ", char)
    }
}

While Go doesn’t have a specific foreach keyword, the for-range loop is the idiomatic way to iterate over collections in Go.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x