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 10 hands-on exercises. Estimated time: 20 minutes.
- What is a pointer — Imagine a library. Every book has a shelf location — a call number like 005.133.GO. A pointer is that call number writte…
- Declare a pointer — The type of a pointer to an `int` is `*int`. A pointer to a `string` is `*string`.\nDeclare a variable `copies` with val…
- aha — change a value through a pointer — If you have a pointer `p` to a variable, you can change the variable's value by writing to `*p`.\n`*p = 99` — sets the v…
- The nil pointer — A pointer that has not been assigned an address has the value `nil`. Using a nil pointer crashes your program.\nRun this…
- Pointers and functions — the copy problem — Here is the problem pointers solve. This function tries to increase the number of book copies, but it receives a copy — …
- Pointers and functions — the fix — Fix the `doubleCopies` function so it actually modifies the original count.\nChange the parameter to `*int` and pass `&c…
- Pointer to a struct — When you have a pointer to a struct, Go lets you use `.` to access fields directly — no need to write `(*book).Title`. G…
- 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.\n`p := new(int)` — …
- Fix the broken function — The `returnBook` function below is supposed to set a book's checked-out status back to false. But it does not work — the…
- Build a library catalog — No starter code. Build a library catalog system:\n1. Define a `Book` struct with `Title` and `Copies` (int)\n2. Write `C…
Go Pointers concepts covered
- The copy problem