Go Tutorial: Pointers
Stop copying. Learn to work with the original. Pointers are simpler than they sound — and more powerful than you expect.
The copy problem
Every time you pass a variable to a function, Go makes a copy. The function works on the copy. The original is untouched.
Most of the time that is fine. But sometimes you need to change the original. Sometimes a variable is huge and copying it is wasteful. Sometimes two parts of your program need to share the same data.
That is where pointers come in.
A pointer does not hold a value. It holds the **address** of a value — where it lives in memory. Change the value at that address and everyone who holds the same address sees the change.
Twelve steps. No magic. Just addresses.
What you'll learn in this Go pointers tutorial
This interactive Go tutorial has 12 hands-on exercises. Estimated time: 20 minutes.
- What is a pointer — Imagine a storage unit. You put your stuff inside. A pointer is not the stuff — it is the unit number written on a Post-…
- Declare a pointer — The type of a pointer to an `int` is `*int`. A pointer to a `string` is `*string`.
- Change a value through a pointer — This is where pointers become useful.
- The nil pointer — A pointer that has not been assigned an address has the value `nil`.
- Pointers and functions — the copy problem — Here is the problem pointers solve.
- Pointers and functions — the fix — Fix the `double` function so it actually modifies the original.
- Pointer to a struct — You used pointer receivers in the Structs chapter. Here is what is happening under the hood.
- new() — another way to create a pointer — `new(T)` allocates memory for a value of type `T`, sets it to its zero value, and returns a pointer to it.
- When to use a pointer — Three rules of thumb:
- Pointer gotcha — the loop variable trap — This is a classic Go bug.
- Fix the broken function — The `resetScore` function below is supposed to set a student's score back to zero. But it does not work — the score stay…
- Build a bank account — No starter code.
Go Pointers concepts covered
- The copy problem