Creating a map with / without make

What 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 any performance considerations?

+18
source share
1 answer

The second form always creates a blank card.

The first form is a special case of a map literal. Cartographic literals allow you 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 without initial values ​​(key / value pairs). This is fully equivalent to:

 m := make(map[T]U) 

In addition, make is the only way to specify the initial capacity of your card, which is greater than the originally assigned number of elements. Example:

 m := make(map[T]U, 50) 

will create a map with enough space for 50 items. This can be useful to reduce future distributions if you know that the map will grow.

+29
source

All Articles