Go Tutorial: Arrays
Store multiple values in one variable. Fixed size, same type, numbered from zero.
One variable, many values
So far every variable has held exactly one value. One name. One score. One age.
But what if you have five scores? Ten names? A hundred items?
You could create a hundred separate variables. Or you could use an array — one variable that holds many values, all in a row, all the same type.
Twelve steps.
What you'll learn in this Go arrays tutorial
This interactive Go tutorial has 12 hands-on exercises. Estimated time: 18 minutes.
- What is an array — Imagine a parking lot with exactly 5 numbered spots: 0, 1, 2, 3, 4.
- Declare an array with values — You can fill an array with values right when you create it.
- Access by index — Array slots are numbered starting at 0 — not 1.
- Update a value — You can change any slot after the array is created. Use the same index syntax — but with `=` instead of just reading.
- The length of an array — `len()` tells you how many slots an array has.
- Loop through an array — Now loops and arrays click together.
- range — the cleaner loop — `for i, v := range array` is a cleaner way to loop.
- The blank identifier _ — Sometimes you only want the value from `range`, not the index.
- Multi-dimensional array — An array can hold other arrays. This creates a grid — rows and columns.
- Arrays are fixed size — This is the one big limitation of arrays: the size is set when you create them and cannot change.
- Find the largest value — A classic loop pattern: go through every element and keep track of the largest one seen so far.
- Build a leaderboard — No starter code.
Go Arrays concepts covered
- One variable, many values