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)
Get Go Programming Language For Dummies 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.