Use this file to discover all available pages before exploring further.
In this article, weβll explore maps in Go. A map is a robust data structure that stores an unordered collection of key-value pairs. Depending on the language, similar structures might be known as associative arrays in PHP, hash tables in Java, or dictionaries in Python. Maps are ideal for quickly retrieving data based on a key, thanks to their efficient implementation using hash tables.Consider a map that associates language codes with their respective languages. For example, the key βenβ might store the value βEnglishβ, and βhiβ could map to βHindiβ.
To declare a map in Go, use the var keyword along with the map type specification. For instance, to declare a map with string keys and integer values, write:
var my_map map[string]int
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.
An alternative to direct initialization is to use the built-in make function. This function allows you to define the map type and, optionally, an initial capacity:
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β:
When executed, the program prints the corresponding values.Itβs important to note that indexing a map in Go returns two values: the value itself and a boolean indicating whether the key exists. The syntax is:
value, found := map_name[key]
If the key does not exist, value will be the zero value for the mapβs value type. Consider the following example:
For the key βenβ, the key exists (true) and its value is 1. For the non-existent key βhhβ, the boolean is false, and the value is 0βthe zero value for an integer.
You can iterate over a map using the range expression, which retrieves both the key and its associated value. In the example below, each key-value pair is printed on a new line:
package mainimport "fmt"func main() { codes := map[string]string{ "en": "English", "fr": "French", "hi": "Hindi", } for key, value := range codes { fmt.Println(key, "=>", value) }}
Running this loop will print all the elements in the map.
Maps in Go are versatile and efficient structures for managing key-value pairs. By understanding how to declare, initialize, access, update, and truncate maps, you can effectively manage data in your Go applications. Continue practicing these concepts to master the use of maps.