
Make a map from Array in Golang
In Go, you can convert an array (or slice) into a map
using a loop. Here’s an example of how to do it:
package main
import "fmt"
func main() {
arrayOfNum := [7]int{100,200,300,400,500,600,700}
fmt.Println("Array",arrayOfNum)
mapOfNum := make(map[int]int)
for i:=0; i<7 ; i++ {
fmt.Printf("Index %d has Value %d \n",i,arrayOfNum[i])
mapOfNum[arrayOfNum[i]] = i
}
fmt.Println(mapOfNum)
}
Output:
Array [100 200 300 400 500 600 700]
Index 0 has Value 100
Index 1 has Value 200
Index 2 has Value 300
Index 3 has Value 400
Index 4 has Value 500
Index 5 has Value 600
Index 6 has Value 700
map[100:0 200:1 300:2 400:3 500:4 600:5 700:6]