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
Release: 2025-01-03 06:53:40
Original
901 people have browsed it

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{}
Copy after login

2. Using the make Function:

var m = make(map[string]int)
Copy after login

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"}
Copy after login

Equivalence and Performance:

The generalized version of your example,

m := map[T]U{}
Copy after login

is equivalent to invoking make:

m := make(map[T]U)
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template