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?
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
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?
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.