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
Golang download image from given URL
How To Make an HTTP Server in Golang?
Split a string at uppercase letters using regular expression in Golang
How to get the current date and time with timestamp in local and other timezones ?
Select single argument from all arguments of variadic function
Different ways for Integer to String Conversions
Example: How to use ReadAtLeast from IO Package in Golang?
How to check lowercase characters in a string in Golang?
Golang Read Write Create and Delete text file
Regular expression to extract all Non-Alphanumeric Characters from a String