Golang Data Collection: “Foreach” iterates through all entries of an array using range


A “for” statement with a “range” clause iterates through all entries of an array, slice, string or map, or values received on a channel. For each entry it assigns iteration values to corresponding iteration variables and then executes the block.

there is no foreach in Golang, But using a for statement with range clause we can iterate through all entries of an array, slice, string or map, or values received on a channel.

The following example shows how to use the range operator in a for loop to implement a foreach loop in Golang:


package main

import "fmt"

var pows = []int{1, 2, 4, 8, 16, 32, 64, 128}
var users = []string{"yuna", "yuni", "yuka", "deisy", "Miyem", "Jhony", "Merry", "Toni"}

func main() {
	for x, value := range pows {
		fmt.Println(x, ":", value)
	}

	for x, user := range users {
		fmt.Println(x, ":", user)
	}
}

Go Output

0 : 1

1 : 2

2 : 4

3 : 8

4 : 16

5 : 32

6 : 64

7 : 128

0 : yuna

 

1 : yuni

2 : yuka

3 : deisy

4 : Miyem

5 : Jhony

6 : Merry

7 : Toni

Success: process exited with code 0.

gommu1.png

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s