Go – Iterate over Range using For Loop
To iterate over elements of a Range in Go, we can use Go For Loop statement.
The syntax to use for loop for a range x
is
for index, element := range x { //code }
We can access the index and element during that iteration inside the for loop block.
Example
In the following example, we will use for loop to iterate over a range of elements.
example.go
package main import "fmt" func main() { x := [6]int{52, 2, 13, 35, 9, 8} for index, element := range x { fmt.Printf("x[%d] = %d\n", index, element) } }
Output
x[0] = 52 x[1] = 2 x[2] = 13 x[3] = 35 x[4] = 9 x[5] = 8
ADVERTISEMENT
Conclusion
In this Golang Tutorial, we learned how to iterate over a range of elements in Go, with For Loop.