Dynamic initialize Map keys

Hi,

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.

Thanks

Yes, it is possible, though you need to use your index i as an index to x and xi, even nested indexing as in m[x[i]].

Also you need to make the map first.

Resulting in this code (I have shortened the inputs as I’m on mobile and fixing the quotes from copying here was annoying):

https://play.golang.org/p/Y-W6m2SLcsP

Thanks, it’s working as expected. I did look inside my code the only difference which I could see is the use of make.

code-shared by you m = make(map[string]int)
code-shared by me =var m map[string]int

I have found explanation as well for the same.

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:

m = make(map[string]int)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.