Home >Backend Development >Golang >Go Maps: `var m = map[string]int{}` vs. `var m = make(map[string]int)`: What's the Difference?
Map Initialization: Unraveling the Differences Between Shortcut and Explicit Creation
The question arises: what starkly differentiates the following two approaches to initializing maps in Go:
var m = map[string]int{}
and
var m = make(map[string]int)
Is the former merely a concise method for speedily initializing fields? Are there any potential performance implications to consider?
Dissecting the Differences
The distinction between these two syntaxes lies in their implications for non-empty maps. While make consistently creates an empty map, the first example leverages a unique feature of map literals: the ability to establish non-empty maps directly. For instance:
m := map[bool]string{false: "FALSE", true: "TRUE"}
To generalize your example, a non-empty map literal with no initial value pairs, like the following:
m := map[T]U{}
is semantically identical to using make explicitly:
m := make(map[T]U)
However, make provides an additional advantage: it permits the specification of an initial capacity for the map that exceeds the count of initially assigned elements. Consider this example:
m := make(map[T]U, 50)
This syntax allocates sufficient space within the map to accommodate up to 50 items. By proactively reserving memory, future allocations can be minimized when anticipating map growth.
The above is the detailed content of Go Maps: `var m = map[string]int{}` vs. `var m = make(map[string]int)`: What's the Difference?. For more information, please follow other related articles on the PHP Chinese website!