chapter four

4 Collection types

 

This chapter covers

  • Ordered collections of data with arrays
  • Dynamic ordered collections using slices
  • Slice manipulation and slice expressions
  • Key-value data with maps

Programming would be very difficult if we could only ever deal with one piece of data at a time. That’s why we have collection types, which help us gather items together.

Go has three different collection types: arrays, slices, and maps. Arrays represent fixed-size lists like those you might find in C or C++, while slices take this a step further and provide an efficient dynamic array type. If you’ve ever wanted a flexible list of items that can expand as needed to suit dynamic data at runtime, slices have your back.

If you need more flexibility, the native map type allows you to store any type of data using a key of any type. If you want to store items by name, size, or any other index, maps are a great solution.

The best part is that these data structures are baked into the language, so they can be used anywhere in your program at any time, without needing to import a special package.

With slices and maps, you can solve a whole host of interesting problems, and once you learn how these data structures work, programming in Go will become fun, fast, and flexible.

4.1 Arrays

An array in Go is a fixed-length collection that contains a contiguous block of elements of any type.

4.1.1 Declaring arrays

4.1.2 Array type and length

4.1.3 Working with array elements

4.1.4 Iterating over arrays with for

4.1.5 Arrays as values

4.1.6 Multidimensional arrays

4.1.7 Passing arrays to functions

4.1.8 The problem with arrays

4.2 Slices

4.2.1 Declaring slices with slice literals

4.2.2 Declaring slices with make

4.2.3 Nil slices

4.2.4 Growing slices with append

4.2.5 Avoiding append surprises

4.2.6 Slice expressions