Lesson 16 · 16 of 20
Pointers · Go
Understand pointers in Go: & to get an address, * to reach the value, functions that change the original, and nil.

A pointer holds the address of a variable, the place where it lives in memory. &score gives that address and ptr := &score stores it; its type is *int, "pointer to int". *ptr reaches the value: 120, the same as score.
Writing through the pointer changes the original variable: *ptr = 150 leaves score at 150, even though that line does not even name it.
In Go arguments are passed by copy. bonusCopy gets an int and adds 50, but only to its copy, which is lost when it returns: score stays at 150. bonus, on the other hand, gets an *int, the address, and *score += 50 changes the original, which becomes 200.
With pointers to structs you do not need the asterisk for fields: inside levelUp, p.Score means (*p).Score. &Player{...} creates the player and gives its address straight away. The zero value of a pointer is nil, meaning it points to nothing; using a nil pointer would stop the program, so it is worth checking first.
Code · main.go
package mainimport "fmt"type Player struct { Name string Score int}// Gets a copy of the number: the change is lost.func bonusCopy(score int) { score += 50 }// Gets the address: *score is the original variable.func bonus(score *int) { *score += 50 }// With a pointer to a struct, p.Score is enough (no * needed).func levelUp(p *Player) { p.Score += 100 }func main() { score := 120 ptr := &score // & gives the address of the variable fmt.Println("score:", score, "| *ptr:", *ptr) *ptr = 150 // * reaches the value behind the address fmt.Println("After *ptr = 150:", score) bonusCopy(score) fmt.Println("After bonusCopy:", score) bonus(&score) fmt.Println("After bonus:", score) ana := &Player{Name: "Ana", Score: 10} levelUp(ana) fmt.Println(ana.Name, "now has", ana.Score, "points") var nobody *Player // a pointer starts as nil fmt.Println("nobody == nil:", nobody == nil)}Output · go run main.go
score: 120 | *ptr: 120 After *ptr = 150: 150 After bonusCopy: 150 After bonus: 200 Ana now has 110 points nobody == nil: true
Key points
&xgives the address ofx; its type is*T.*preads or changes the valueppoints to.- Pass a pointer so a function can change the original.
- With a pointer to a struct,
p.Fieldis enough. - A pointer with no value is
nil.
Exercise
Write func swap(a, b *int), which swaps two variables, and try it; then func resetScore(p *Player), which sets the score back to zero.