Print index and element or data from Array, Slice and Map
Below is a short program to print index or element from Array Slice and Map in golang.
Each time you will run the below program the order of index of map may give different result. While it remain same for array and slice.
Example
package main
import "fmt"
func main() {
fmt.Println("\n###### Array ######\n")
intArray := [5]int{1,2,3,4,5}
for index,element := range intArray{
fmt.Println(index,"=>",element)
}
fmt.Println("\n###### Slice ######\n")
intSlice := make([]int,5)
intSlice[0]=1
intSlice[1]=2
intSlice[2]=3
intSlice[3]=4
intSlice[4]=5
for index,element := range intSlice{
fmt.Println(index,"=>",element)
}
fmt.Println("\n###### Map ######\n")
intStrMap := make(map[string]int)
intStrMap["A"]=0
intStrMap["B"]=1
intStrMap["C"]=2
intStrMap["D"]=3
intStrMap["E"]=4
for index,element := range intStrMap{
fmt.Println(index,"=>",element)
}
}
Output
###### Array ######
0 => 1
1 => 2
2 => 3
3 => 4
4 => 5
###### Slice ######
0 => 1
1 => 2
2 => 3
3 => 4
4 => 5
###### Map ######
D => 3
E => 4
A => 0
B => 1
C => 2
C:\golang\codes>go run example29.go
###### Array ######
0 => 1
1 => 2
2 => 3
3 => 4
4 => 5
###### Slice ######
0 => 1
1 => 2
2 => 3
3 => 4
4 => 5
###### Map ######
C => 2
D => 3
E => 4
A => 0
B => 1