How to use for and foreach loop?
A "for loop" in golang is a statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement i.e. it is the repetition of a process within a go program.
Example
package main
import (
"fmt"
)
func main() {
arrayOne := [3]string{"Apple", "Mango", "Banana"}
fmt.Println("\n---------------Example1--------------------\n")
for index,element := range arrayOne{
fmt.Println(index)
fmt.Println(element)
}
strDict := map[string]string {"Japan" : "Tokyo", "China" : "Beijing", "Canada" : "Ottawa"}
fmt.Println("\n---------------Example2--------------------\n")
for index,element := range strDict{
fmt.Println("Index :",index," Element :",element)
}
fmt.Println("\n---------------Example3--------------------\n")
for key := range strDict {
fmt.Println(key)
}
fmt.Println("\n---------------Example4--------------------\n")
for _, value := range strDict {
fmt.Println(value)
}
j :=0
fmt.Println("\n---------------Example5--------------------\n")
for range strDict {
fmt.Println(j)
j++
}
}
Output
---------------Example1--------------------
0
Apple
1
Mango
2
Banana
---------------Example2--------------------
Index : Japan Element : Tokyo
Index : China Element : Beijing
Index : Canada Element : Ottawa
---------------Example3--------------------
Japan
China
Canada
---------------Example4--------------------
Tokyo
Beijing
Ottawa
---------------Example5--------------------
0
1
2
Most Helpful This Week
How to count number of repeating words in a given String?
How to write backslash in Golang string?
Different ways to convert Byte Array into String
Regular expression to extract all Non-Alphanumeric Characters from a String
Converting Int data type to Float in Go
How to get the current date and time with timestamp in local and other timezones ?