What exactly is the difference between
var m = map[string]int{}
and
var m = make(map[string]int)
Is the first just a shortcut for faster field initialization? Are there performance considerations?
Start by heading to maps.google.com. Click on the menu icon on the top left hand side of the screen and select “Your Places.” (The menu icon is just to the left of the search bar on the top left hand side of your screen.) Select the maps tab. Navigate to the very bottom of that window and select “Create a Map.”
Initializing map using map literals: Map literal is the easiest way to initialize a map with data just simply separate the key-value pair with a colon and the last trailing colon is necessary if you do not use, then the compiler will give an error.
The second form always creates an empty map.
The first form is a special case of a map literal. Map literals allow to create non empty maps:
m := map[bool]string{false: "FALSE", true: "TRUE"}
Now your (generalized) example:
m := map[T]U{}
is a map literal with no initial values (key/value pairs). It's completely equivalent to:
m := make(map[T]U)
Additionally, make
is the only way to specify an initial capacity to your map which is larger than the number of elements initially assigned. Example:
m := make(map[T]U, 50)
will create a map with enough space allocated to hold 50 items. This can be useful to reduce future allocations, if you know the map will grow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With