Gopher

Range for loop in Golang

Published on 10 May 2020
Last Updated on 10 May 2020

Range form of the for loop in Golang can be used for iterating over an array while reading index and value of the individual array elements.

Accessing index and value in a range for loop is demonstrated in the example given below.

package main

import "fmt"

func main()  {
	var alphabets=[]string{"a","b","c","d"}

	for index, value :=range alphabets{
		fmt.Println("\nindex is:",index)
		fmt.Println("value is:",value)
	}
}

Program output

Above program produces following output:

index is: 0
value is: a

index is: 1
value is: b

index is: 2
value is: c

index is: 3
value is: d

Accessing only the index in range form of the for loop

If a programmer is only interested in accessing index of the element in a for loop then refer to following example to learn how that is done:

package main

import "fmt"

func main()  {
	var alphabets=[]string{"x","y","z"}

	for index :=range alphabets{
		fmt.Println("\nindex is:",index)
	}
}

Program output

Above program produces following output:

index is: 0

index is: 1

index is: 2

Accessing only the value in range form of the for loop

Refer to example given below to learn how to only access the value of an element in the array using the range form of the for loop.

package main

import "fmt"

func main() {
	var alphabets = []string{"x", "y", "z"}
	for _, value := range alphabets {
		fmt.Println("value is:", value)
	}
}

Program output

Above program produces following output:

value is: x
value is: y
value is: z