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
Most Helpful This Week
How to Unmarshal nested JSON structure?
Regular expression to validate the date format in "dd/mm/yyyy"
How to get Dimensions of an image type jpg jpeg png or gif ?
How to use wildcard or a variable in our URL for complex routing?
How to update content of a text file?
Example to use Weekday and YearDay function
How to fix race condition using Atomic Functions in Golang?
How to copy a map to another map?
Functions mess (recursive anonymous function) in Golang
Data encryption with AES-GCM