Go Tutorial: Slices
Arrays but flexible. The collection type you will use in almost every Go program you ever write.
Arrays that can grow
In the last chapter you learned arrays — fixed size, same type, never changes.
Slices are the same idea but without the fixed part. They can grow, shrink, and be built up piece by piece at runtime.
In practice, you will use slices far more than arrays. Almost every list in Go is a slice.
Sixteen steps. By the end you will build a working todo list.
What you'll learn in this Go slices tutorial
This interactive Go tutorial has 9 hands-on exercises. Estimated time: 22 minutes.
- Declare an empty slice — A slice is like an array but with no fixed size — the brackets are empty. Run this to see an empty slice ready to receiv…
- Declare with values — `books := []string{"Dune", "1984", "Moby Dick"}` — no size number needed. Go counts for you. Create an `authors` slice w…
- append — add to the end — `books = append(books, "Neuromancer")` adds a book. Critical: you must reassign the result. Append three books one at a …
- len and cap 🤯 — Every slice has a length (`len`) and a capacity (`cap`). When you append and run out of space, Go doubles the capacity. …
- Access and update by index — Slices use the same zero-indexed syntax as arrays. A patron returned a damaged book — replace the book at index 2 with "…
- Loop with range — `for i, v := range books` gives you index and value. Loop through and print each as `"Book 1: Dune"`, `"Book 2: 1984"`, …
- Slicing a slice — `books[1:3]` gives you indexes 1 and 2 (high end is exclusive). Print just the middle three books from the collection.
- copy() — the real duplicate 🤯 — Here's a trap: `b := a` does NOT copy a slice. Both point to the same data. Use `copy(dst, src)` for a genuine separate …
- Build a library catalog — Start with 4 books, append "Brave New World", then print a numbered catalog from 1 to 5.
Go Slices concepts covered
- Arrays that can grow