Lesson 19. The ever-versatile map

 

After reading lesson 19, you’ll be able to

  • Use maps as collections for unstructured data
  • Declare, access, and iterate over maps
  • Explore some uses of the versatile map type

Maps come in handy when you’re searching for something, and we’re not just talking about Google Maps (www.google.com/mars/). Go provides a map collection with keys that map to values. Whereas arrays and slices are indexed by sequential integers, map keys can be nearly any type.

Note

This collection goes by several different names: dictionaries in Python, hashes in Ruby, and objects in JavaScript. Associative arrays in PHP and tables in Lua serve as both maps and conventional arrays.

Maps are especially useful for unstructured data where the keys are determined while a program is running. Programs written in scripting languages tend to use maps for structured data as well—data where the keys are known ahead of time. Lesson 21 covers Go’s structure type, which is better suited for those cases.

Consider this

Maps associate a key with a value, which is handy for an index. If you know the title of a book, iterating through every book in an array could take some time, just like looking through every shelf of every aisle of a library or bookstore. A map keyed by book title is faster for that purpose.

What are some other situations in which a map from keys to values could be useful?

19.1. Declaring a map

19.2. Maps aren’t copied

19.3. Preallocating maps with make

19.4. Using maps to count things

19.5. Grouping data with maps and slices

19.6. Repurposing maps as sets

Summary