Chapter 8
Establishing Relationships Using Maps
IN THIS CHAPTER
Seeing how to create maps in Go
Creating and sorting a map of structs
In earlier chapters, I fill you in on arrays and slices, where the position of items is important, and items are accessed by their locations. A map, on the other hand, is a hash table that stores data in an associative manner. Items in a map are not accessed according to their positions. Instead, you use keys (a set of unique value that identifies the elements in a map). Maps make adding and removing items extremely easy.
In this chapter, I show you how to work with maps in Go, create a map of structs, and sort a map based on its content.
Creating Maps in Go
A Go map type has the following syntax:
map[keyType] valueType
Here is an example of a map variable that stores a collection of int values with the key that is of the type string:
package main var heights map[string]int func main() { }
Because the map type is a reference type, you need to first initialize it using the make() function before you can use it:
heights = make(map[string]int)
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access
By default, the map variable (