Saturday, May 18, 2024
HomeGolangForeach loop in Go (Golang)

Foreach loop in Go (Golang)



There isn’t a foreach loop and foreach key phrase in Go, however the traditional for loop will be tailored to work in the same method. Utilizing the vary key phrase, you’ll be able to create the vary type of the for loop that may be very helpful when iterating over a slice or map. This type of loop has the type of:

for <index>, <worth> := vary <array/slice> {
    ...
}

the place:

  • <index> is a numeric ordinal quantity that returns 0 for the primary ingredient within the array, 1 for the second, and so forth
  • <worth> is a replica of a slice/array ingredient at that <index>

For maps, the for vary loop has <key> as an alternative of <index>:

for <key>, <worth> := vary <map> {
    ...
}

the place:

  • <key> is the important thing of a given map entry
  • <worth> is a replica of a map ingredient at that <key>

Instance

Within the following instance, we iterate by way of a slice and map to print every ingredient. We don’t want the <index> to print the slice gadgets, so it may be ignored utilizing the clean identifier (underscore). In such a case, the for vary loop is nearly equivalent to the foreach identified from different programming languages. When printing map gadgets, we use the <key> and <worth> to output the colour (worth) of the fruit (key).

func primary() {
    // array foreach loop
    fruits := []string{"apple", "strawberry", "raspberry"}

    for _, fruit := vary fruits {
        fmt.Printf("Fruit: %sn", fruit)
    }

    // map foreach loop
    fruitColors := map[string]string{
        "apple":      "inexperienced",
        "strawberry": "purple",
        "raspberry":  "pink",
    }

    for fruit, colour := vary fruitColors {
        fmt.Printf("%s colour is %sn", fruit, colour)
    }
}

Output:

Fruit: apple
Fruit: strawberry
Fruit: raspberry
apple colour is inexperienced
strawberry colour is purple
raspberry colour is pink
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments