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).

  1. monthdays := map[string]int{
  2. "Jan": 31, "Feb": 28, "Mar": 31,
  3. "Apr": 30, "May": 31, "Jun": 30,
  4. "Jul": 31, "Aug": 31, "Sep": 30,
  5. "Oct": 31, "Nov": 30, "Dec": 31, 1
  6. }

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.

  1. year := 0
  2. for _, days := range monthdays 1
  3. year += days
  4. }
  5. 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].