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 convert Colorful PNG image to Gray-scale?
How to create thumbnail of an image?
How to fetch an Integer variable as String in Go?
Get Set and Clear Session in Golang
Convert specific UTC date time to PST, HST, MST and SGT
Encoding and Decoding using json.Marshal and json.Unmarshal
How to read current directory using Readdir?
How to Convert string to float type in Go?
How to verify a string only contains letters, numbers, underscores, and dashes in Golang?
Golang String Concatenation