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
Example: How to use ReadAtLeast from IO Package in Golang?
How to create thumbnail of an image?
Example: How to use TeeReader from IO Package in Golang?
How to set, get, and list environment variables?
Print index and element or data from Array, Slice and Map
Example to use Weekday and YearDay function
Split URL and Get Parameters from URL
Copy an array by value and reference into another array
Golang HTML parser
How to add and update elements in Map?