Declaring a Map
To declare a map in Go, use thevar keyword along with the map type specification. For instance, to declare a map with string keys and integer values, write:
This syntax initializes a nil map. The zero value of a map in Go is nil, meaning it doesn’t contain any keys. Trying to add a key-value pair to a nil map will result in a runtime error.
Adding Values to a Map
Let’s observe what happens when we try to add a key-value pair to an uninitialized (nil) map. Consider this example:Initializing a Map with Values
To initialize a map with initial key-value pairs, you can use the shorthand literal syntax:- We declare a map named
codesusing the shorthand declaration operator. - The map is populated with string keys and values inside curly braces.
Using the make Function
An alternative to direct initialization is to use the built-inmake function. This function allows you to define the map type and, optionally, an initial capacity:
Determining the Length of a Map
To obtain the number of key-value pairs in a map, utilize the built-inlen function:
Accessing Map Values
To access a map value, refer to its key enclosed in square brackets. For instance, to display the values for the keys “en”, “fr”, and “hi”:value will be the zero value for the map’s value type. Consider the following example:
Adding and Updating Map Entries
Adding a new key-value pair to a map is straightforward; simply assign a value to a new key:Deleting Map Entries
To remove a key-value pair from a map, use the built-indelete function. This function takes the map and the key to delete as its arguments:
delete.
Iterating Over a Map
You can iterate over a map using therange expression, which retrieves both the key and its associated value. In the example below, each key-value pair is printed on a new line:
Truncating a Map
Truncating a map involves clearing all its elements. There are two common methods to achieve this:Method 1: Deleting Each Key Iteratively
Loop through the map and delete each key:Method 2: Re-initializing the Map
Alternatively, reinitialize the map using themake function: