How to use for and foreach loop in Golang?

There is only one looping construct in Golang, and that is the for loop. The for loop in Golang has three components, which must be separated by semicolons (;), those are:

  • The initialization statement: which is executed before the first iteration. e.g. i := 0
  • The condition expression: which is executed just before every iteration. e.g. i < 5
  • The Post statement: which is executed at the end of every iteration. e.g. i++

There is no need for any parentheses for enclosing those three components, but to define a block we must use braces { }.

for i := 0 ; i < 5 ; i++{
         // statements to execute......
}

The initialization and post statements are optional.

i:=0
for ; i < 5;{
i++
}

You can use for loop as while loop in Golang. Just drop all the semicolons.

i := 0
for i < 5 {
i++
}

Infnite Loop: If there is no condition statement, the loop becomes an infinite loop.



for {
}

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

package main
  
import "fmt"
  
// function to print numbers 0
// to 9 and print the sum of 0 to 9
func main() {
  
    // variable to store the sum
    sum := 0
  
    // this is a for loop which runs from 0 to 9
    for i := 0; i < 10; i++ {
  
        // printing the value of 
        // i : the iterating variable
        fmt.Printf("%d ", i)
  
        // calculating the sum
        sum += i
    }
    fmt.Printf("\nsum = %d", sum)
}

chevron_right


Output:

0 1 2 3 4 5 6 7 8 9 
sum = 45

In Golang there is no foreach loop instead, the for loop can be used as “foreach“. There is a keyword range, you can combine for and range together and have the choices of using the key or value within the loop.

Syntax:

for <key>, <value> := range <container>{

}

Here,

  • key and value: It can be any variable you want to choose.
  • container: It can be any variable which is an array, list, map, etc.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

package main
  
import "fmt"
  
// Driver function to show the
// use of for and range together
func main() {
  
    // here we used a map of integer to string
    mapp := map[int]string{1: "one", 2: "two", 3: "three"}
  
    // integ act as keys of mapp
    // spell act as the values of
    // mapp which is mapped to integ
  
    for integ, spell := range mapp {
  
        // using integ and spell as
        // key and value of the map
        fmt.Println(integ, " = ", spell)
    }
}

chevron_right


Output:

1  =  one
2  =  two
3  =  three

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

package main
  
import "fmt"
  
// Driver function to show the
// use of for and range together
func main() {
  
    // declaring an array of integers
    arra := []int{1, 2, 3, 4}
  
    // traversing through the array
    for index, itr := range arra {
      
        // the key or value variables
        // used in for syntax
        // depends on the container. 
        // If its an array or list,
        // the key refers to the index...
        fmt.Print(index, " : ", itr, "\n")
    }
  
    // if we use only one 
    // variable in the for loop,
    // it by default refers to 
    // the value in the container.
    for itr := range arra {
  
        fmt.Print(it, " ")
    }
}

chevron_right


Output:

0 : 1
1 : 2
2 : 3
3 : 4
1 2 3 4 



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.