Collections in Go

Collections is where your programs learn to keep many values together.

In this chapter, you will:

  • keep a fixed number of values in an array
  • read, change, loop through and compare arrays
  • understand why the size of an array is part of its type
  • grow and share lists with slices
  • store values by key with maps

What each lesson covers:

  • Arrays: Go arrays: fixed-size lists of one type. Declare and create them, read, update and loop through elements, and learn length, zero values, copying, comparing and 2D arrays.
  • Slices: Go slices: growable lists built on arrays. Create them, append, copy, len and cap, the underlying array, slicing, removing and inserting, and arrays vs slices.
  • Maps: Go maps: key-value pairs. Create them with literals and make, add, update, delete and look up values, check keys with comma-ok, loop with range, and use zero values and nested maps.

This chapter has 3 lessons. Plan on about 75 minutes, with 10 exercises to check what you learned. Every example is real Go code: change it, run it again and compare the output, which is the fastest way to learn how each feature behaves.

Simple lesson: finish this chapter and you can store and work with lists of values.

Lessons in this section

  1. Arrays

    Go arrays: fixed-size lists of one type. Declare and create them, read, update and loop through elements, and learn length, zero values, copying, comparing and 2D arrays.

    • Explain what an array is and why its size is fixed
    • Declare and create arrays in four ways
    • Read, update and loop through elements safely
    • Predict length and zero values, and how arrays are copied
  2. Slices

    Go slices: growable lists built on arrays. Create them, append, copy, len and cap, the underlying array, slicing, removing and inserting, and arrays vs slices.

    • Explain what slices are and why they are used
    • Create slices with literals, make and slicing
    • Use append, copy, len and cap
    • Explain length, capacity and the underlying array
  3. Maps

    Go maps: key-value pairs. Create them with literals and make, add, update, delete and look up values, check keys with comma-ok, loop with range, and use zero values and nested maps.

    • Explain maps and key-value pairs
    • Create maps with literals and make
    • Add, update, delete and look up values
    • Check if a key exists with comma-ok