Chapter 13. Data Structure Recipes

13.0 Introduction

Go has four basic types of data structures: arrays, slices, maps, and structs. Chapter 12 discussed structs and this chapter will cover arrays, slices, and maps. Following is some background information on these data structures before getting into specific recipes for using them.

Arrays

Arrays are data structures that represent an ordered sequence of elements of the same type. Array sizes are static; they are set when the array is defined and cannot be changed subsequently. In Go, arrays are values. This is an important difference, because in some languages an array is a pointer to the first item in the array. This means if you pass an array to a function you will be passing a copy of the array, and this could be expensive.

Slices

Slices are data structures that also represent an ordered sequence of elements. Slices are built on top of arrays and are used much more often than arrays because of their flexibility. Slices have no fixed length. Internally, a slice is a struct that consists of a pointer to an array, the length of the segment of the array, and the capacity of the underlying array.

Maps

Maps are data structures that associate the values of one type (called the key) with values of another type (called the value). Such data structures are very common in many other programming languages, called by different names like hash table, hash map, and dictionary. Internally, a map is a pointer to runtime.hmap structure. ...

Get Go Cookbook 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.