Lesson 13Manipulating Maps

In the previous lessons, several methods for organizing and accessing data have been presented, including arrays, structs, and slices. Another common structure for storing data is a hash map, or simply a map. In this lesson, we will look at the use of maps and how to program them using Go.

DEFINING A MAP

Most major programming languages support maps as they are arguably one of the most important data structures for storing data. A map is a collection of paired values, where one value in each pair is a key that identifies the other value in the pair.

You can use maps to reference values through their key as a way of avoiding referencing the value itself. You can also use maps to change one value that is associated with another value.

Go supports maps through the built-in map data type, using the basic structure:

map[KeyType]ValueType

The key type and the value type can be different, but all keys must be of the same type and all values must be of the same type. The values in a map can be of any type (even another map). Map keys can be any of the following types:

  • Boolean
  • Numeric
  • String
  • Pointers
  • Structs or arrays that contain the previous types listed
  • Channels (more on this later)
  • Interface types (more ...

Get Job Ready Go 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.