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 you could only ever deal with one piece of data at a time. This is the reason we have collection types, which help us gather items together.

Go has three different collection types: arrays, slices and maps. Arrays represent fixed-sized lists like 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 you might want, maps are a great solution.

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

Between 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 Array Elements

4.1.4 Iterating 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

4.2.7 Copying Slices with copy

4.2.8 Avoiding Runtime Panics When Accessing Slice Values

4.2.9 Nil Slices Versus Empty Slices