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 8 hands-on exercises. Estimated time: 18 minutes.
- What is an array — An array is a shelf with a fixed number of slots, all the same type. Run this to see five slots all starting at zero.
- Declare with values — Fill a shelf right when you create it: `books := [3]string{"Dune", "Neuromancer", "Snow Crash"}`. Change the titles to y…
- Access by index — Shelf slots start at 0, not 1. `books[0]` is the first, `books[2]` is the third. Print each title on its own line using …
- Update a value — Change any slot with `shelf[index] = value`. Change slot [1] from 65 to 88 and run it to see the before and after.
- Loop through an array — Use a `for` loop with `len()` to print every element automatically. Add the loop to print all five shelf values.
- range — the cleaner loop — `for i, v := range shelf` gives you index and value. No manual counter, no `len()`. Change this loop to use `range`.
- Arrays are fixed size 🤯 — This program tries to put 5 books in a 3-slot shelf. Run it, read the error, then fix it by changing `[3]` to `[5]`.
- Find the thickest book — Loop through page counts and track the largest. Start with `pages[0]` as the thickest, then update if you find a bigger …
Go Arrays concepts covered
- One variable, many values