Hence, learning how to work with maps can be crucial as a go developer. This article will try to answer a few questions regarding maps in the Go programming language.
How to create a map
You can create a map in Go using the syntax shown below:
We start with the keyword map followed by the data type of the key. Next, we set the data type for the values and, finally, a pair of curly braces.
The above syntax creates an empty map.
For example, to create an empty map with int type as the keys and string type as values, we can do:
If you do not want an empty map, you can assign values during creation as shown below:
The second method to create a map is to literal Go map. An example is as shown:
The above creates an empty map.
Go also provides you with the make() method, which you can use to create a map. The example below creates an empty map of string-float pairs.
How to Print a Map
The simplest operation you can perform with a map is to print it out. For that, we can use the Println method from the fmt package.
import"fmt"
funcmain() {
my_map := map[int]string{
1: "a",
2: "b",
3: "c",
4: "d",
5: "e",
}
fmt.Println(my_map)
}
The above code should print the map stored in the “my_map” variable. The resulting output is as shown:
How to Iterate over Keys and Values of a Map
Iterating over a map means we get each consecutive key-value pair in the map. We can accomplish this using the classic for loop and the range operator.
An example is as shown:
1: "a",
2: "b",
3: "c",
4: "d",
5: "e",
}
for key, value := range my_map {
fmt.Printf("Key: %d Value: %s\n", key, value)
}
In Go, calling the range operator on a map returns two values: the key and the value. Using the for loop allows us to get each key and value in the map.
The resulting output:
Key: 1 Value: a
Key: 2 Value: b
Key: 3 Value: c
Key: 4 Value: d
How to Iterate Keys only in a Map
As mentioned, using the range operator over a map returns the key and value pairs. However, we can retrieve only one value, as shown below:
fmt.Println("Key: ", key)
}
The above example should only return the keys in the map as:
Key: 3
Key: 4
Key: 5
Key: 1
How to Iterate Values in a Map
Similarly, you can retrieve the values of the map using the syntax below:
fmt.Println("Value: ", value)
}
Output:
Value: b
Value: c
Value: d
Value: e
Conclusion
You can iterate over the key and values of a map using the range operator. You can also filter and get only the keys or values shown in this guide.
Happy coding!