Why do I have to initialize a map

Hi,

I started learning Go lang today through the Tour. I bumped some code in Maps chapter and I don’t really understand why a map has to be “initialized” using the make built-in function.

package main

import "fmt"

var myMap map[string]string
var myArray [10]int

func main() {
	myMap = make(map[string]string)
	myMap["foo"] = "bar"

	fmt.Println(myMap)

	myArray[0] = 123

	fmt.Println(myArray)
}

There is a myArray defined a I can use it right away.

1, Why there has to be myMap = make(map[string]string)?
2, Doesn’t that lead to potential errors when users have to write the map[string]string exactly 2 times?

Thanks for answers!

1 Like

Hi,

From documentation :

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.

You cand find the entire text here

2 Likes

Oh I see. Thank you. :slight_smile:

1 Like

In your case, you can declare and init a map in the same line. For example
var myMap = map[string]string{“foo”: “bar”}
and get rid of make an init MyMap in main function

In this case Go infers the type of MyMap and you do not need to specify it,
Map types are reference types, so if you only declares it, its value is nil so you need to use make to create it

2 Likes

Right. Thanks for the info. Is it a common practice to declare maps in global scope and then initialize them in the main function or do people usually write only var myMap = make(map[string]string) in the “main” function?

1 Like

Is it a common practice to declare maps in global scope and then initialize them in the main function or do people usually write only var myMap = make(map[string]string) in the “main” function?

For what it is worth:
I rarely see global variable is the Go code I have looked at. But that may just be my experience.

2 Likes

Global scope is usually a bad idea and shouldn’t be used…

3 Likes

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