A Go map is equivalent to the well-known hash table found in many other programming languages. The main advantage of maps is that they can use any data type as their index, which in this case is called a map key or just a key. Although Go maps do not exclude any data types from being used as keys, for a data type to be used as a key, it must be comparable, which means that the Go compiler must be able to differentiate one key from another or, put simply, that the keys of a map must support the == operator. The good news is that almost all data types are comparable. However, as you can understand, using the bool data type as the key to a map will definitely limit your options! Additionally, using floating-point numbers as keys might present problems caused by the precision used among different machines and operating systems.
You can create a new empty map with string keys and int values with the help of the make() function:
iMap = make(map[string]int)
Alternatively, you can use the next map literal in order to create a new map that will be populated with data:
anotherMap := map[string]int { "k1": 12 "k2": 13 }
You can access the two objects of anotherMap as anotherMap["k1"] and anotherMap["k1"]. You can delete an object of a map using the delete() function:
delete(anotherMap, "k1")
You can iterate over all of the elements of a map using the following technique:
for key, value := range iMap { fmt.Println(key, value) }
The Go code of usingMaps.go will illustrate the use of maps in more detail. The program will be presented in three parts. The first part is shown in the following Go code:
package main import ( "fmt" ) func main() { iMap := make(map[string]int) iMap["k1"] = 12 iMap["k2"] = 13 fmt.Println("iMap:", iMap) anotherMap := map[string]int{ "k1": 12, "k2": 13, }
The second part of usingMaps.go contains the following code:
fmt.Println("anotherMap:", anotherMap) delete(anotherMap, "k1") delete(anotherMap, "k1") delete(anotherMap, "k1") fmt.Println("anotherMap:", anotherMap) _, ok := iMap["doesItExist"] if ok { fmt.Println("Exists!") } else { fmt.Println("Does NOT exist") }
Here you see a technique that allows you to determine whether a given key is in the map or not. This is a vital technique because without it you would not know whether a given map has the required information or not.
Additionally, you can see the delete() function in action-calling the same delete() statement multiple times does not make any difference and does not generate any warning messages.
The last part of the program is as follows:
for key, value := range iMap { fmt.Println(key, value) } }
Here you see the use of the range keyword on a map, which is pretty elegant and handy.
If you execute usingMaps.go, you will get the following output:
$ go run usingMaps.go iMap: map[k1:12 k2:13] anotherMap: map[k1:12 k2:13] anotherMap: map[k2:13] Does NOT exist k1 12 k2 13