Home > Backend Development > Golang > Does `map` or `make` Matter When Creating Maps in Go?

Does `map` or `make` Matter When Creating Maps in Go?

Patricia Arquette
Release: 2024-12-01 05:57:11
Original
601 people have browsed it

Does `map` or `make` Matter When Creating Maps in Go?

Does make Matter When Creating Maps?

When creating maps in Go, developers have two options:

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

While the former may seem like a shortcut for faster field initialization, both options have subtle differences.

Map Literals vs. make

The first form is a special case of a map literal, which allows the creation of non-empty maps with specific key-value pairs. For instance:

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

In contrast, the second form using make always creates an empty map. It's equivalent to the map literal with no initial values, such as:

m := map[string]int{}
Copy after login

Initial Capacity

The key distinction between the two approaches lies in the ability to specify an initial capacity. make allows you to allocate space for a specific number of items, even if they're not initially assigned. This can help reduce future allocations if you anticipate the map growing significantly. For example:

m := make(map[string]int, 50)
Copy after login

This creates a map with enough space for 50 items, potentially reducing allocations as the map expands.

Best Practice

In general, the choice between the two methods depends on the situation. If you're creating an empty map where performance is not critical, either option will suffice. However, if you anticipate a large map or want to set the initial capacity, using make is recommended.

The above is the detailed content of Does `map` or `make` Matter When Creating Maps in Go?. 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