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

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

Patricia Arquette
Patricia ArquetteOriginal
2025-01-03 06:53:40909browse

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.

The above is the detailed content of Go Maps: `map[string]int{}` vs. `make(map[string]int)`: What's the Difference?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn