"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Go Maps: The difference between `map[string]int{}` and `make(map[string]int)`

Go Maps: The difference between `map[string]int{}` and `make(map[string]int)`

Posted on 2025-04-21
Browse:991

Go Maps: `map[string]int{}` vs. `make(map[string]int)`: What's the Difference?

Understanding the Difference Between map Initialization with and without make

When dealing with maps in Go, you may encounter two distinct forms of initialization:

1. Using a Map Literal:

var m = map[string]int{}

2. Using the make Function:

var m = make(map[string]int)

Functional Differences:

The primary distinction lies in the way maps are initialized. The second form, using make, always produces an empty map. However, the first form is a unique case of a map literal. Map literals can construct maps with initial key-value pairs. For instance:

m := map[bool]string{false: "FALSE", true: "TRUE"}

Equivalence and Performance:

The generalized version of your example,

m := map[T]U{}

is equivalent to invoking make:

m := make(map[T]U)

In terms of performance, the two approaches behave identically when creating empty maps.

Initial Capacity:

The primary advantage of using make is the ability to specify an initial capacity. This can be done by adding an integer argument to the make function:

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

This initializes a map with space allocated for 50 elements. Pre-allocating can reduce future memory allocations if you anticipate map growth.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3