How to use for and foreach loop in Golang?
Last Updated :
23 Nov, 2021
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++
}
Infinite Loop: If there is no condition statement, the loop becomes an infinite loop.
for {
}
Example:
Go
package main
import "fmt"
func main() {
sum := 0
for i := 0 ; i < 10 ; i++ {
fmt.Printf( "%d " , i)
sum += i
}
fmt.Printf( "\nsum = %d" , sum)
}
|
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 choice 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:
Go
package main
import "fmt"
func main() {
mapp := map [int] string { 1 : "one" , 2 : "two" , 3 : "three" }
for integ, spell := range mapp {
fmt.Println(integ, " = " , spell)
}
}
|
Output:
1 = one
2 = two
3 = three
Example 2:
Go
package main
import "fmt"
func main() {
arra := []int{ 1 , 2 , 3 , 4 }
for index, itr := range arra {
fmt.Print(index, " : " , itr, "\n" )
}
for itr := range arra {
fmt.Print(it, " " )
}
}
|
Output:
0 : 1
1 : 2
2 : 3
3 : 4
1 2 3 4
Share your thoughts in the comments
Please Login to comment...