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
Regular expression to extract DNS host-name or IP Address from string
How to read input from console line?
Generate a Keygen of 256 bits
How to check lowercase characters in a string in Golang?
Different ways for Integer to String Conversions
Convert Int data type to Int16 Int32 Int64
Regular expression to extract domain from URL
Sample program to create csv and write data
Anonymous Functions in Golang
Convert Float32 to Float64 and Float64 to Float32