How can we use the foreach loop in Golang
In this shot, we will learn how to use a foreach loop in Golang.
There is no foreach loop explicitly present in Golang.
However, we can use the for statement with the range clause to iterate through an array, slice, or map.
Syntax
If the index and element are both necessary, then we will use the following syntax:
for index, element := range slice or map {
}
If the index is not necessary, then we will use _, which is known as an anonymous placeholder:
for _, element := range slice or map {
}
Example
In the following example, we will traverse through a slice fruits. Then, we will print each element in a new line, using for-range.
Code
package main//import fmt packageimport("fmt")//program execution starts herefunc main(){//declare and initialize slicefruits := []string{"apple", "orange", "grapes", "guava"}//traverse through the slice using for and rangefor _, element := range fruits{//Print each element in new linefmt.Println(element)}}
Code explanation
-
Line 5: We import the
fmtpackage, which we will use to print statements. -
Line 9: The program execution starts from the
main()function. -
Line 12: We declare and initialize the slice
fruits, which contains the elements of string data type. -
Line 15: We traverse through the slice
fruits, using thefor-rangeloop and providingfruitsafter the range keyword. Since we are not using the index, we will use an anonymous placeholder,_. -
Line 18: We access the element present inside the
forloop and print it in a new line.