Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating map with/without make

Tags:

go

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?

like image 733
Era Avatar asked Jun 06 '13 10:06

Era


People also ask

How can I create a map?

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

How do you initialize a map in go?

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.


1 Answers

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.

like image 139
zzzz Avatar answered Oct 05 '22 23:10

zzzz