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 16 hands-on exercises. Estimated time: 22 minutes.
- The problem with arrays — Arrays are great when you know the size upfront. But what if you do not?
- Declare an empty slice — A slice looks almost identical to an array — but with no number in the brackets.
- make() — create a slice with a known size — When you know how many slots you need upfront, use `make`.
- Declare with values — When you already have the values, declare and fill in one shot.
- append — add to the end — This is the most important slice operation.
- len and cap — Every slice has two numbers:
- Access and update by index — Slices use the same index syntax as arrays. Zero-indexed. Read with `s[i]`. Write with `s[i] = value`.
- Loop with range — Looping over a slice works exactly like looping over an array.
- Slicing a slice — You can cut out a portion of a slice using `[low:high]` syntax.
- copy() — the real duplicate — Here is a trap that catches almost everyone.
- Remove an element — Go has no built-in remove function for slices. You build it yourself.
- Slice of slices — A slice can hold other slices. Each inner slice can be a different length — unlike a 2D array which must be rectangular.
- Todo list — start — Time to build something real.
- Todo list — add more tasks — New tasks keep coming in.
- Todo list — complete a task — You finished "Reply to emails" — time to remove it from the list.
- Todo list — final list — One new task just came in: "Plan the weekend".
Go Slices concepts covered
- Arrays that can grow