Maps
Many other languages have a type similar to maps built-in. For instance, Perlhas hashes, Python has its dictionaries, and C++ also has maps (as part of thelibraries). In Go we have the map
type. A map
can bethought of as an array indexed by strings (in its most simple form).
monthdays := map[string]int{
"Jan": 31, "Feb": 28, "Mar": 31,
"Apr": 30, "May": 31, "Jun": 30,
"Jul": 31, "Aug": 31, "Sep": 30,
"Oct": 31, "Nov": 30, "Dec": 31, 1
}
The general syntax for defining a map is map[<from type>]<to type>
. Here, wedefine a map that converts from a string
(month abbreviation) to an int
(number of days in that month). Note that the trailing comma at 1 isrequired.
Use make
when only declaring a map: monthdays := make(map[string]int)
. A mapis a reference type.
For indexing (“searching”) the map, we use square brackets. For example, supposewe want to print the number of days in December: fmt.Printf("%d\n",monthdays["Dec"])
If you are looping over an array, slice, string, or map a, range
clause will help you again, it returns the key and corresponding valuewith each invocation.
year := 0
for _, days := range monthdays 1
year += days
}
fmt.Printf("Numbers of days in a year: %d\n", year)
At 1 we use the underscore to ignore (assign to nothing) the key returned byrange
. We are only interested in the values from monthdays
.
To add elements to the map, you would add new month with: monthdays["Undecim"]= 30
. If you use a key that already exists, the value will be silentlyoverwritten: monthdays["Feb"] = 29
. To test for existence you would use the following: value, present := monthdays["Jan"]
.If the key “Jan” exists, present
will be true. It’s more Go like to namepresent
“ok”, and use: v, ok := monthdays["Jan"]
. In Go we call this the“comma ok” form.
You can remove elements from the map
:delete(monthdays, "Mar")
7. In general thesyntax delete(m, x)
will delete the map entry retrieved by the expressionm[x]
.