Download our all in one automation tool for various social media websites.
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)
}
}
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
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)
}
}
Above program produces following output:
index is: 0
index is: 1
index is: 2
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)
}
}
Above program produces following output:
value is: x
value is: y
value is: z