Maps

The Map data type in Go is equivalent to the well-known hash table found in other programming languages. The main advantage of maps is that they can use almost any data type as their index, which in this case is called a key. For a data type to be used as a key, it must be comparable.

So, let's take a look at an example Go program, named maps.go, which we will use for illustrative purposes. The first part of maps.go contains the preamble Go code you would expect:

package main 
 
import ( 
   "fmt" 
) 
 
func main() { 
 

Then, you can define a new empty map that has strings as its keys and integer numbers as values, as follows:

   aMap := make(map[string]int) 

Post this, you can add new key and value pairs to the aMap map, as follows:

 aMap["Mon"] = ...

Get Go Systems Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.