Golang Tutorial 10: Pointers
Pointers in Go with runnable examples: & and *, when to pass a pointer, nil pointers, pointer vs value receivers, new(expr) from Go 1.26, the range loop trap and a short look at escape analysis with -gcflags=-m. Small exercise at the end.
Pointers scare people who come to Go from Python or JavaScript, and they bore people who come from C. Go's pointers sit in the middle: no pointer arithmetic, a garbage collector cleans up, but you still decide when a function gets a copy and when it gets the original. In this blog we will look at & and *, when to pass a pointer, nil pointers, pointer and value receivers, the new builtin (it got a nice change in Go 1.26), a loop trap and a quick look at escape analysis.
Level: beginner. You should know structs from Tutorial 7 and slices from Tutorial 9. I ran every example on Go 1.27.3 (1.27.4 is the latest patch, same behaviour here).
mkdir pointersdemo && cd pointersdemo
go mod init example.com/pointersdemo
mkdir basics passing receivers nilptr newexpr escape loopvar exercise
& and *
A pointer holds the address of a value. &x gives you the address of x. *p gives you the value the pointer points at, and you can also assign through it.
package main
import "fmt"
func main() {
x := 10
p := &x
fmt.Println("x =", x)
fmt.Println("p points to", *p)
fmt.Printf("p is a %T\n", p)
*p = 25
fmt.Println("x is now", x)
q := p
*q++
fmt.Println("x after *q++ =", x, "same pointer?", p == q)
}
x = 10
p points to 10
p is a *int
x is now 25
x after *q++ = 26 same pointer? true
*int is read as "pointer to int". Copying a pointer (q := p) copies the address, not the value, so both point at the same x. That's really all there is to the syntax.
Passing a pointer to a function
Go passes everything by value. A function always gets a copy of what you give it. If you give it a struct, it gets a copy of the struct. If you give it a pointer, it gets a copy of the pointer, which still points at your struct.
package main
import "fmt"
type Account struct {
Owner string
Balance int
}
func depositByValue(a Account, amount int) {
a.Balance += amount
}
func depositByPointer(a *Account, amount int) {
a.Balance += amount // same as (*a).Balance
}
func main() {
acc := Account{Owner: "aravind", Balance: 100}
depositByValue(acc, 50)
fmt.Println("after value:", acc.Balance)
depositByPointer(&acc, 50)
fmt.Println("after pointer:", acc.Balance)
// Slices and maps already carry a pointer inside them.
m := map[string]int{"a": 1}
bump(m)
fmt.Println("map after bump:", m["a"])
}
func bump(m map[string]int) {
m["a"]++
}
after value: 100
after pointer: 150
map after bump: 2
The deposit by value got lost. I think this is the most common pointer bug for people new to Go, and the compiler can't help you because both versions are valid code.
Notice a.Balance in depositByPointer. Go dereferences struct pointers for you, you don't need to write (*a).Balance.
The map case works without a pointer because a map value is already a small handle to the real data. Slices are similar: the header (pointer, length, capacity) is copied, but the elements are shared. We saw in the last tutorial what happens when you append inside a function, the length change gets lost because the header was a copy.
So when do I pass a pointer? My rules are simple.
- The function needs to change the caller's value.
- The struct is big, say a config with dozens of fields, and you call the function in a hot loop.
- You need to say "nothing here", which is what
nilis for.
For small structs that are only read, pass by value. It's often just as fast, and it means the function can't change your data behind your back.
Pointer receivers and value receivers
Methods get a receiver, and the receiver follows the same rules as any other parameter.
package main
import "fmt"
type Counter struct {
name string
n int
}
// Value receiver: works on a copy.
func (c Counter) IncValue() { c.n++ }
// Pointer receiver: changes the original.
func (c *Counter) Inc() { c.n++ }
func (c Counter) String() string { return fmt.Sprintf("%s=%d", c.name, c.n) }
func main() {
c := Counter{name: "clicks"}
c.IncValue()
c.IncValue()
fmt.Println(c)
c.Inc() // Go takes &c for us
c.Inc()
fmt.Println(c)
cp := &c
cp.Inc()
fmt.Println(cp.String(), c.String())
counters := map[string]Counter{"home": {name: "home"}}
// counters["home"].Inc() does not compile: cannot take the address of a map value
h := counters["home"]
h.Inc()
counters["home"] = h
fmt.Println(counters["home"])
}
clicks=0
clicks=2
clicks=3 clicks=3
home=1
IncValue did nothing useful, same as depositByValue. c.Inc() works on a plain variable because Go quietly takes its address. It goes the other way too: cp.String() calls a value method on a pointer.
The map part needs a word. I tried counters["home"].Inc() first, just to see what happens, and the build failed with this:
./main.go:9:19: cannot call pointer method Inc on Counter
Map values aren't addressable. The map may move its entries around when it grows, so Go won't hand out a pointer to one. You either copy the value out, change it and put it back (as above), or store pointers in the map: map[string]*Counter.
The usual advice, which I follow, is to pick one style per type. If any method needs a pointer receiver, give all of them pointer receivers. Mixing them works, but it makes the method sets confusing once you start using interfaces, which is the topic of Tutorial 11.
nil pointers
The zero value of a pointer is nil. Reading through a nil pointer panics.
package main
import "fmt"
type Config struct {
Port int
}
func portOrDefault(c *Config) int {
if c == nil {
return 8080
}
return c.Port
}
func main() {
var c *Config
fmt.Println("c is nil:", c == nil)
fmt.Println("port:", portOrDefault(c))
fmt.Println("port:", portOrDefault(&Config{Port: 9000}))
fmt.Println(c.Port) // panics
}
c is nil: true
port: 8080
port: 9000
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x2 addr=0x0 pc=0x100983654]
goroutine 1 [running]:
main.main()
.../nilptr/main.go:22 +0x114
exit status 2
The panic tells you the file and line, so these are easy to find once they happen. The hard part is that they happen at run time. Check for nil where a nil is a valid input, like portOrDefault does, and otherwise make sure constructors never return a nil pointer without an error next to it.
new, and new(expr) in Go 1.26
new(T) allocates a zero T and returns a *T. For years that was all it did, which was annoying for optional fields. If a struct has a *int field to mean "not set", you couldn't write &30. You needed a temporary variable or a little helper like func ptr[T any](v T) *T. Go 1.26 lets new take an expression.
package main
import "fmt"
type Options struct {
Timeout *int // nil means "use the default"
Name *string
}
func main() {
p := new(int)
fmt.Println(*p)
// Go 1.26+: new accepts an expression.
opts := Options{Timeout: new(30), Name: new("shorty")}
fmt.Println(*opts.Timeout, *opts.Name)
// The old way needed a helper or a temporary variable.
t := 30
old := Options{Timeout: &t}
fmt.Println(*old.Timeout)
}
0
30 shorty
30
The go line in go.mod decides which language version you get. To check, I set it to go 1.25 and built again.
./main.go:5:20: new(30) requires go1.26 or later (-lang was set to go1.25; check go.mod)
Nice clear message. If your module still says older version, bump it before using this.
The range loop trap (and why it's mostly gone)
Taking the address of a loop variable used to be a famous Go bug. Since Go 1.22 every iteration gets its own variable, so the old bug of all pointers ending up the same is fixed. But there is still a trap here.
package main
import "fmt"
type user struct{ name string }
func main() {
users := []user{{"asha"}, {"ravi"}, {"meena"}}
var ptrs []*user
for _, u := range users {
ptrs = append(ptrs, &u) // pointer to the loop copy
}
ptrs[0].name = "changed"
fmt.Println(users[0].name, ptrs[0].name, ptrs[2].name)
var real []*user
for i := range users {
real = append(real, &users[i]) // pointer into the slice
}
real[0].name = "changed"
fmt.Println(users[0].name)
}
asha changed meena
changed
u is a copy of the element, so &u points at the copy. Changing it doesn't touch users. If you want to change the slice elements, take &users[i].
I wanted to see the old behaviour for myself, so I ran a tiny loop that collects &v for []int{1, 2, 3} with go 1.21 in go.mod. It printed 3 3 3. With go 1.22 or later it prints 1 2 3. Same compiler, different answer, only because of that one line in go.mod. Worth knowing when you upgrade an old module.
Escape analysis in one paragraph
Go decides for you whether a value lives on the stack (cheap, freed when the function returns) or on the heap (managed by the garbage collector). If a pointer to a local value can outlive the function, the value "escapes" to the heap. You can ask the compiler what it decided:
package main
import "fmt"
type point struct{ X, Y int }
func sum(p point) int {
return p.X + p.Y
}
func newPoint(x, y int) *point {
p := point{X: x, Y: y}
return &p
}
func main() {
a := point{1, 2}
total := sum(a)
b := newPoint(3, 4)
println(total, b.X)
fmt.Println(a)
}
go build -gcflags=-m -o /dev/null ./escape
escape/main.go:7:6: can inline sum
escape/main.go:11:6: can inline newPoint
escape/main.go:18:14: inlining call to sum
escape/main.go:19:15: inlining call to newPoint
escape/main.go:21:13: inlining call to fmt.Println
escape/main.go:12:2: moved to heap: p
escape/main.go:21:13: ... argument does not escape
escape/main.go:21:14: a escapes to heap
Returning &p from newPoint is perfectly safe in Go (it would be a bug in C), and the compiler moves p to the heap for it. Two things in that output surprised me. There's no heap move reported inside main for b, because newPoint got inlined and then the compiler could see the pointer never leaves main. And a escapes only because I passed it to fmt.Println, which takes any. Don't go chasing these for normal code. It matters when you profile a hot path and see lots of small allocations, and that is a topic for a later post.
Exercise
Build a singly linked list with type Node struct { Val int; Next *Node }. Write push(head *Node, v int) *Node that adds to the front, and reverse(head *Node) *Node that reverses the list in place, without allocating new nodes. Pushing 1 to 5 and printing should give 5 4 3 2 1, and after reverse 1 2 3 4 5.
My solution is below. Try first, it's a good check that you can follow pointers in your head.
package main
import "fmt"
type Node struct {
Val int
Next *Node
}
func push(head *Node, v int) *Node {
return &Node{Val: v, Next: head}
}
func reverse(head *Node) *Node {
var prev *Node
for head != nil {
next := head.Next
head.Next = prev
prev = head
head = next
}
return prev
}
func print(head *Node) {
for n := head; n != nil; n = n.Next {
fmt.Print(n.Val, " ")
}
fmt.Println()
}
func main() {
var list *Node
for i := 1; i <= 5; i++ {
list = push(list, i)
}
print(list)
print(reverse(list))
}
5 4 3 2 1
1 2 3 4 5
Notice var list *Node starts as nil and push still works, since a nil Next just means "end of list". Yes, I named a function print, which shadows the builtin. It compiles, go vet is happy with it, but I wouldn't do it outside a toy.
If you want a real program to read with these ideas in mind, the handler code in the standard library REST API post uses *http.Request and pointer receivers all over.