Maps are unordered collection of key value pairs. In other languages they are known with various names viz. hash tables, dictionaries and associative arrays. Here’s an example of a Key-Value pair – Working Days of the week denoted by integer keys.
Key | Value |
1 | Monday |
2 | Tuesday |
3 | Wednesday |
4 | Thursday |
5 | Friday |
In the above table Key = 1 denotes a value of Monday. Key = 3 denotes a value of Wednesday.
Let us see how we can represent the above using Go Maps:
Code-Snippet# 1
package main import "fmt" func main() { // Map declaration day := make(map[int]string) //Assigning values day[1] = "Monday" day[2] = "Tuesday" day[3] = "Wednesday" day[4] = "Thursday" day[5] = "Friday" //Fetching values fmt.Println(day[1]) fmt.Println(day[3]) }
Output
Monday
Wednesday
Code Explanation
How to Declare a Map?
day := make(map[int]string)
You can read this as the variable day is a map of int keys to string values.
Here we’ve used builtin make function with Key type as int and value type as string as shown above. Assigning and fetching values are similar to simple Arrays.
Important Note: Maps are reference types. So, the value of the variable day above is nil. It doesn’t point to an initialized map.
The above Code-Snippet# 1 can be made shorter and precise as follows:
Code-Snippet# 2
package main import "fmt" func main() { // Map declaration day := map[int]string { //Assigning values 1 : "Monday", 2 : "Tuesday", 3 : "Wednesday", 4 : "Thursday", 5 : "Friday", } //Fetching values fmt.Println(day[1]) fmt.Println(day[3]) }
The output of the Code-Snippet# 2 (shared above) is exactly same as what we have seen for Code-Snippet# 1.
Let us see some more interesting operations with Golang Maps. Read the comments to easily understand the code.
Code-Snippet# 3
package main import "fmt" func main() { // Map declaration day := map[int]string { //Assigning values 1 : "Monday", 2 : "Tuesday", 3 : "Wednesday", 4 : "Thursday", 5 : "Friday", } //Fetching the Map - all key-value pairs fmt.Println("Map: ", day) //Total number of key-values in the Map fmt.Println("Length of the map: ", len(day)) //Check if Key=6 exists in the Map _, isPresent := day[6] fmt.Println("Does Key 6 Exist: ", isPresent) //Deleting Key=3 delete(day,3) fmt.Println("Map: ", day) fmt.Println("Length of the map: ", len(day)) //Check if Key=3 exists in the Map _, exist := day[3] fmt.Println("Does Key 3 Exist: ", exist) }
Output
Map: map[1:Monday 2:Tuesday 3:Wednesday 4:Thursday 5:Friday]
Length of the map: 5
Does Key 6 Exist: false
Map: map[5:Friday 1:Monday 2:Tuesday 4:Thursday]
Length of the map: 4
Does Key 3 Exist: false
You can find a few more beginner level code examples of Go Maps here. Please comment with your feedback.
Basant Singh
Latest posts by Basant Singh (see all)
- Go Maps Introduction for Beginners - May 20, 2015
- Go Programming – Arrays and Slices - May 11, 2015
- Golang Switch Case with Sample Code - May 1, 2015