Go For Each
Go language does not have a builtin forEach kind of statement. But the nearest kind of syntax could be achieved using for loop with range as shown in the following.
for index, element := range x { //code }
During each iteration, we get access to the index of the element, and the element itself.
Examples
In the following program, we take a slice of integers in slice1
and loop for each element in the slice.
example.go
package main import "fmt" func main() { x := []int{10, 20, 30, 40, 50} for index, element := range x { fmt.Println(index, " - ", element) } }
Output
0 - 10 1 - 20 2 - 30 3 - 40 4 - 50
Let us do the same for an array. Take an array of integers and loop for each of the element in it.
example.go
package main import "fmt" func main() { x := [5]int{11, 22, 33, 44, 55} for index, element := range x { fmt.Println(index, " - ", element) } }
Output
0 - 11 1 - 22 2 - 33 3 - 44 4 - 55
If we do not need index while looping, we may provide underscore symbol instead of index.
example.go
package main import "fmt" func main() { x := [5]int{11, 22, 33, 44, 55} for _, element := range x { fmt.Println(element) } }
Output
11 22 33 44 55
The same process holds true for element as well.
example.go
package main import "fmt" func main() { x := [5]int{11, 22, 33, 44, 55} for index, _ := range x { fmt.Println(index) } }
Output
0 1 2 3 4
Conclusion
In this Golang Tutorial, we learned how to write a for each loop in Go, with the help of example programs.