Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
communitycreator
slice
foreach

How can we use the foreach loop in Golang

Gutha Vamsi Krishna

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 package
import(
  "fmt"
)

//program execution starts here
func main(){

  //declare and initialize slice
  fruits := []string{"apple", "orange", "grapes", "guava"}

  //traverse through the slice using for and range
  for _, element := range fruits{

    //Print each element in new line
    fmt.Println(element)
  }
}

Code explanation

  • Line 5: We import the fmt package, 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 the for-range loop and providing fruits after 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 for loop and print it in a new line.

RELATED TAGS

golang
communitycreator
slice
foreach
RELATED COURSES

View all Courses

Keep Exploring