These are the notes for Go episode 11. In episode 9 a discount function changed the price, and the change vanished outside the function. Today we fix it properly with pointers. You will learn memory addresses, the address-of operator &, pointer types like *int, dereferencing with *, passing pointers to functions, why Go has no pointer arithmetic, nil pointers and the nil pointer dereference panic, new, pointers to structs, value vs pointer semantics, and when to use pointers. Every example runs as-is in the SyntaxPilot compiler (language: Go); outputs and errors are from real runs (Go 1.24).
The problem: the vanishing discount
package main
import "fmt"
func discount(price int) {
price = price - 50
}
func main() {
price := 500
discount(price)
fmt.Println("price:", price)
}
price: 500
Go passes every argument by value: the parameter gets a copy (a photocopy) of the argument, and the function changes only its copy. Returning the new value works (episode 9), but sometimes a function must change the caller's own variable.
Think of a painter. Hand him a photo of your house and he paints the photo: your house stays the same (a copy). Hand him your address and he walks to the real house and paints it. Give a function the address of your variable, and it can change the real thing.
| Painting your house | In Go |
|---|---|
| A photo of your house | discount(price): a copy of the value |
| Your home address | discount(&price): the address of the value |
Memory addresses
Picture the cloakroom at a railway station: rows of lockers, each with a number. Your computer's memory (RAM, random-access memory) is the same: billions of numbered boxes, each holding one byte.
- Every variable lives somewhere in memory. The number of its box is its memory address; what's inside is its value.
- In Go,
&in front of a variable means "the address of". It's the address-of operator. - Addresses are printed in hexadecimal (base 16, digits 0-9 and a-f), starting with
0x.
package main
import "fmt"
func main() {
price := 500
fmt.Println("value: ", price)
fmt.Println("address:", &price)
}
value: 500
address: 0xc000010100
Your address will be different, and may change from run to run. That's fine: we never care about the exact number, only about holding on to it.
Pointers: & and *
Write the locker number on a slip of paper. The slip isn't your bag; it tells you where the bag is.
| At the cloakroom | In Go | Name |
|---|---|---|
| A slip saying "locker 18" | p := &price |
a pointer: a variable that stores an address |
| Walk to locker 18 and open it | *p |
dereference: use the value at the address |
| "This slip is for a bag locker" | *int |
a pointer type: pointer to an int |
package main
import "fmt"
func main() {
price := 500
p := &price
fmt.Printf("p is a %T\n", p)
fmt.Println("p holds:", p)
fmt.Println("*p reads:", *p)
*p = 450
fmt.Println("price is now:", price)
}
p is a *int
p holds: 0xc000010100
*p reads: 500
price is now: 450
We never wrote price = ..., yet price changed: we wrote through its address.
Three symbols, three meanings
| You see | Where | Means |
|---|---|---|
&x |
in an expression | the address of x |
*int |
in a type | pointer to an int |
*p |
in an expression | the value p points to (read or write) |
A pointer has a type: a *int can only point to an int, a *string only to a string.
Fixing the discount
package main
import "fmt"
func discount(p *int) {
*p = *p - 50
}
func main() {
price := 500
discount(&price)
fmt.Println("price:", price)
}
price: 450
Strictly speaking, Go still passed by value: it copied the address into p. But a copy of an address points to the same locker, so the change lands on the original. (Go has no "pass by reference"; passing a pointer gives the same effect.)
Forget the & and Go stops you:
package main
import "fmt"
func discount(p *int) {
*p = *p - 50
}
func main() {
price := 500
discount(price)
fmt.Println("price:", price)
}
# command-line-arguments
./main.go:11:14: cannot use price (variable of type int) as *int value in argument to discount
Two pointers, one variable (aliasing)
Two slips can carry the same locker number:
package main
import "fmt"
func main() {
price := 500
p := &price
q := &price
fmt.Println(p == q)
*q = 300
fmt.Println(*p, price)
}
true
300 300
- Pointers are comparable:
p == qis true when they hold the same address (or are bothnil). - A change through
qis visible throughpand throughprice. Two names reaching the same variable is called aliasing. Powerful, but remember that a change in one place shows up everywhere.
Swapping two values
A waiter swapped two orders. A swap that takes values swaps only its copies:
package main
import "fmt"
func swap(a, b string) {
a, b = b, a
}
func main() {
tea, coffee := "tea", "coffee"
swap(tea, coffee)
fmt.Println(tea, coffee)
}
tea coffee
With pointers, it swaps the originals. Pointers work with any type: *string, *int, *Wallet.
package main
import "fmt"
func swap(a, b *string) {
*a, *b = *b, *a
}
func main() {
tea, coffee := "tea", "coffee"
swap(&tea, &coffee)
fmt.Println(tea, coffee)
}
coffee tea
No pointer arithmetic
In C you can do maths on addresses (p + 1 walks to the next box). It's powerful and a famous source of crashes and security holes. Go doesn't allow it:
package main
import "fmt"
func main() {
price := 500
p := &price
p = p - 50
p++
fmt.Println(*p)
}
# command-line-arguments
./main.go:8:9: invalid operation: p - 50 (mismatched types *int and untyped int)
./main.go:9:5: invalid operation: p++ (non-numeric type *int)
A Go pointer is not a number, so it can't wander into memory that isn't yours. To change the value, dereference: *p = *p - 50, *p++.
nil pointers
A pointer declared without a value gets its zero value, which for pointers is nil: it points nowhere. A blank slip.
package main
import "fmt"
func main() {
var p *int
fmt.Println(p == nil, p)
fmt.Println(*p)
}
true <nil>
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x491b4d]
goroutine 1 [running]:
main.main()
/tmp/main.go:8 +0x6d
exit status 2
Dereferencing a nil pointer is a panic (Go stopping the program because of a run-time error). SIGSEGV, a segmentation violation, is the operating system's signal for touching memory you're not allowed to touch. This is the most common pointer bug in Go. Check before you use it.
new
new(T) creates a fresh variable of type T set to its zero value, and returns its address.
package main
import "fmt"
func show(p *int) {
if p == nil {
fmt.Println("no value yet")
return
}
fmt.Println("value:", *p)
}
func main() {
show(nil)
p := new(int)
show(p)
*p = 7
show(p)
}
no value yet
value: 0
value: 7
show(nil) passes a nil pointer directly. p := new(int) is the same as var x int; p := &x, without needing a name for x.
Pointers to structs
Quick preview of episode 19: a struct is like a form with named fields. It groups related values under one name.
type Wallet struct {
Owner string
Balance int
}
You make one with Wallet{Owner: "Asha", Balance: 100} and read a field with a dot: w.Balance. Structs are copied just like ints:
package main
import "fmt"
type Wallet struct {
Owner string
Balance int
}
func addMoney(w Wallet, amount int) {
w.Balance += amount
}
func main() {
asha := Wallet{Owner: "Asha", Balance: 100}
addMoney(asha, 50)
fmt.Println(asha.Owner, asha.Balance)
}
Asha 100
The whole wallet was photocopied. With a pointer:
package main
import "fmt"
type Wallet struct {
Owner string
Balance int
}
func addMoney(w *Wallet, amount int) {
w.Balance += amount
}
func newWallet(owner string) *Wallet {
w := Wallet{Owner: owner}
return &w
}
func main() {
asha := Wallet{Owner: "Asha", Balance: 100}
addMoney(&asha, 50)
fmt.Println(asha.Owner, asha.Balance)
ravi := newWallet("Ravi")
addMoney(ravi, 20)
fmt.Println(ravi.Owner, ravi.Balance)
}
Asha 150
Ravi 20
- Automatic dereference: with a pointer to a struct,
w.Balancemeans(*w).Balance. Go inserts the*for you. - Returning the address of a local variable is safe in Go. In C it's a classic bug (the variable dies when the function returns). Go's compiler notices that the address escapes the function and keeps the wallet alive, on the heap (the memory area for values that outlive a single call), just like the closure's captured
countin episode 10. This analysis is called escape analysis. - A common Go convention is a constructor function named
NewXornewXthat returns*X(episode 20).
Value vs pointer semantics
package main
import "fmt"
func main() {
a := 10
b := a
b = 99
fmt.Println("copy: a =", a, "b =", b)
p := &a
*p = 99
fmt.Println("pointer: a =", a)
}
copy: a = 10 b = 99
pointer: a = 99
- Value semantics: assigning or passing copies the value; everyone has their own. Safe and simple.
- Pointer semantics: sharing an address; everyone sees and changes the same value. Needed for changes to be visible.
When should you use a pointer?
- The function must change the caller's value:
discount(&price),addMoney(&asha, 50). - The value is big: copying a large struct on every call is wasteful; a pointer is 8 bytes on a 64-bit machine.
- You need "no value":
nilcan mean "not set yet". - Otherwise, use plain values. They're simpler, and a value can never be
nil.
Mini project: a money transfer
The video's version moves money between two balances through two *int pointers:
package main
import "fmt"
func transfer(from, to *int, amount int) bool {
if *from < amount {
return false
}
*from -= amount
*to += amount
return true
}
func main() {
asha, ravi := 300, 50
fmt.Println(transfer(&asha, &ravi, 200))
fmt.Println(transfer(&ravi, &asha, 999))
fmt.Println("Asha:", asha, "Ravi:", ravi)
}
true
false
Asha: 100 Ravi: 250
Both balances changed because transfer worked on the originals through their addresses. Extension: the same with wallets, two *Wallet parameters:
package main
import "fmt"
type Wallet struct {
Owner string
Balance int
}
func transfer(from, to *Wallet, amount int) bool {
if from.Balance < amount {
return false
}
from.Balance -= amount
to.Balance += amount
return true
}
func main() {
asha := Wallet{"Asha", 300}
ravi := Wallet{"Ravi", 50}
fmt.Println(transfer(&asha, &ravi, 200))
fmt.Println(transfer(&ravi, &asha, 999))
fmt.Println(asha, ravi)
}
true
false
{Asha 100} {Ravi 250}
Wallet{"Asha", 300} is a positional struct literal (values in field order). Next, refuse a negative or zero amount.
Common mistakes (and the real error messages)
| You wrote | Real error / what happens | Fix |
|---|---|---|
discount(price) when it wants *int |
cannot use price (variable of type int) as *int value in argument to discount |
discount(&price) |
p = p - 50 |
invalid operation: p - 50 (mismatched types *int and untyped int) |
*p = *p - 50 |
p++ on a pointer |
invalid operation: p++ (non-numeric type *int) |
*p++ |
var p *int; fmt.Println(*p) |
panic: runtime error: invalid memory address or nil pointer dereference |
if p != nil, or p = new(int) |
func f(w Wallet) expecting to change w |
no error: the copy changes | func f(w *Wallet), call f(&w) |
printing p expecting the value |
prints an address like 0xc000010100 |
print *p |
Practice
- Write
swap(a, b *int)that swaps two ints. - Write
double(p *int)and call it on three variables. - Print a
nilpointer, then write a function that guards against it. - Write
deposit(w *Wallet, amount int) boolthat refuses amounts ≤ 0.
Solutions
- Go's multiple assignment makes it one line:
package main
import "fmt"
func swap(a, b *int) {
*a, *b = *b, *a
}
func main() {
x, y := 1, 2
swap(&x, &y)
fmt.Println(x, y)
}
2 1
2.
package main
import "fmt"
func double(p *int) {
*p *= 2
}
func main() {
a, b, c := 3, 10, 21
double(&a)
double(&b)
double(&c)
fmt.Println(a, b, c)
}
6 20 42
- See
showin thenewsection above.
4.
package main
import "fmt"
type Wallet struct {
Owner string
Balance int
}
func deposit(w *Wallet, amount int) bool {
if amount <= 0 {
return false
}
w.Balance += amount
return true
}
func main() {
w := Wallet{"Asha", 100}
fmt.Println(deposit(&w, 50), deposit(&w, -20), w.Balance)
}
true false 150
Quick quiz
What does this print?
func main() {
x := 1
p := &x
q := p
*q = 5
fmt.Println(x, *p)
}
- A.
1 1 - B.
1 5 - C.
5 5 - D. compile error
Answer
C. 5 5. q := p copies the pointer, and a copy of an address is the same address. *q = 5 changes x, and *p reads x.
Interview questions
- What is a pointer? What do
&and*do? - What does
*intmean in a type, and*pin an expression? - Is Go pass by value or pass by reference? How do you let a function change the caller's variable?
- Why doesn't Go allow pointer arithmetic?
- What is the zero value of a pointer? What happens when you dereference it?
- What does
new(T)return? - When are two pointers equal? What is aliasing?
- Why can you write
w.Balanceinstead of(*w).Balance? - Is it safe to return the address of a local variable in Go? Why?
- When should you use a pointer, and when a value?
Glossary
| Term | Meaning | Example |
|---|---|---|
| Memory (RAM) | the computer's working storage: numbered boxes holding bytes | where price lives |
| Memory address | the number of the box where a variable lives | 0xc000010100 |
| Hexadecimal | base 16 numbers, digits 0-9 and a-f; written with 0x |
0xff = 255 |
Address-of operator & |
gives the address of a variable | &price |
| Pointer | a variable that stores an address | p := &price |
| Pointer type | the type of a pointer: * + the type it points to |
*int, *Wallet |
Dereference *p |
use the value at the address p holds | *p = 450 |
| Pass by value | arguments are copied into parameters | discount(price) |
| Pass by reference | (not in Go) the function gets the caller's variable itself | simulated with pointers |
| Pointer arithmetic | maths on addresses; not allowed in Go | p + 1 is an error |
| nil | the zero value of a pointer: points nowhere | var p *int |
| Nil pointer dereference | using *p when p is nil; a panic |
panic: runtime error: invalid memory address or nil pointer dereference |
| Panic | Go stopping the program because of a run-time error | the nil dereference above |
| SIGSEGV / segmentation violation | the OS signal for touching memory you may not use | in the panic message |
| new(T) | creates a zero-valued T and returns its address | p := new(int) |
| Struct | a type grouping named fields (episode 19) | type Wallet struct { ... } |
| Field | one named value inside a struct | Balance |
| Struct literal | a struct value written in code | Wallet{Owner: "Asha", Balance: 100} |
| Pointer to struct | a pointer whose target is a struct | *Wallet |
| Automatic dereference | w.Balance works on a *Wallet |
w.Balance += amount |
| Escape analysis | the compiler working out which values must outlive their function | return &w is safe |
| Heap | memory for values that outlive a single function call | where w goes |
| Aliasing | two names (pointers) reaching the same variable | p and q both &price |
| Constructor function | a function that creates and returns a new value | newWallet("Ravi") |
| Value semantics | copying: each owner has its own value | b := a |
| Pointer semantics | sharing: everyone uses one value through its address | p := &a |
Summary
- Every variable lives at a memory address.
&xgives it; a pointer stores it. *Tis the pointer type;*pdereferences, reading or writing the value.- Pass
&xso a function can changex. Go still copies, but it copies the address. - Go has no pointer arithmetic. The zero value of a pointer is
nil, and dereferencing it panics. new(T)returns a pointer to a fresh zero value. With pointers to structs,w.Fielddereferences automatically, and returning&localis safe.- Use pointers to change the caller's value, to avoid copying big values, or to express "no value". Otherwise, prefer values.
Next episode: arrays. A week of chai sales, fixed-size lists, indexes, copies, comparisons and grids.