Understanding the Distinction Between Map Creation with and without make
In Go, there are two ways to initialize a map:
var m = map[string]int{}
var m = make(map[string]int)
While these may appear similar, they have different implications and practical considerations.
Empty Map Creation with make
The second form, make(map[string]int), always creates an empty map. This is a straightforward way to initialize a map with no initial key-value pairs.
Non-Empty Map Literals
The first form, map[string]int{}, is a special case of a map literal. Map literals allow the creation of non-empty maps with pre-defined key-value pairs. For example:
m := map[bool]string{false: "FALSE", true: "TRUE"}
Empty Map Literals
Now, the example in your question:
m := map[T]U{}
It's a map literal with no initial values (key/value pairs). This is equivalent to:
m := make(map[T]U)
Therefore, the first form is essentially a shortcut for the latter when creating an empty map.
Performance Considerations
In terms of performance, both approaches are comparable for creating an empty map. However, make has the additional flexibility to specify an initial capacity. By specifying a larger capacity, make pre-allocates enough space in memory to hold a certain number of elements. This can be beneficial to reduce future allocations if you know the map is likely to grow.
The above is the detailed content of What's the Difference Between `map[T]U{}` and `make(map[T]U)` in Go?. For more information, please follow other related articles on the PHP Chinese website!