Junior
How to properly declare a map in Go?
sobes.tech AI
Answer from AI
A map can be declared in several ways:
-
Using
var:// declaring a map without initialization // value is nil var myMap map[string]int -
Using
make:// declaring and initializing an empty map myMap := make(map[string]int) // declaring and initializing a map with a specified capacity // can improve performance with a large number of elements myMapWithCapacity := make(map[string]int, 100) -
Using a literal:
// declaring and initializing with initial values myMapWithValues := map[string]int{ "key1": 1, "key2": 2, } // declaring and initializing an empty map // equivalent to make(map[string]int) emptyMapLiteral := map[string]int{}
Differences between methods:
| Method | Default initialization | Capacity specification | Adding initial values |
|---|---|---|---|
var |
nil |
No | No |
make |
Empty map | Yes | No |
Literal {} |
Empty map | No | Yes |
It is important to remember that a map declared with var without initialization (nil) cannot be used to add or retrieve elements. Such operations will cause a panic. It must be initialized with make or a literal.