I want to know if we can initialize keys in the Map dynamically using loops.
let’s suppose i have below code:
package main
import “fmt”
func main() {
xi := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
x := []string{“r”, “a”, “j”, “s”, “i”, “n”, “g”, “h”, “s”}
var m map[string]int
i := 0
for i = range xi {
// m[i] = x[i]
}
fmt.Println(m)
}
My requirement is to use the string array as map keys and int array as corresponding values. Let me know if my understanding is correct and if this is feasible to do.
This variable m is a map of string keys to int values:
var m map[string]int
Map types are reference types, like pointers or slices, and so the value of m above is nil ; it doesn’t point to an initialized map. A nil map behaves like an empty map when reading, but attempts to write to a nil map will cause a runtime panic; don’t do that. To initialize a map, use the built in make function: