0Pricing
Go Academy · Lesson

Pointer Receivers on Methods

Mutating struct state via pointer receivers

Pointer Receivers on Methods is a free Go Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Recap: Value vs Pointer Receiver

A value receiver operates on a copy of the struct. A pointer receiver operates on the original. Use pointer receivers whenever a method needs to modify state.

Mutation with Pointer Receiver

Only a pointer receiver can mutate the struct:

package main
import "fmt"

type Stack struct{ items []int }

func (s *Stack) Push(v int) { s.items = append(s.items, v) }
func (s *Stack) Pop() int {
    n := len(s.items) - 1
    v := s.items[n]
    s.items = s.items[:n]
    return v
}

func main() {
    var st Stack
    st.Push(1); st.Push(2)
    fmt.Println(st.Pop()) // 2
}

Consistency Rule

If any method on a type needs a pointer receiver, all methods should use pointer receivers. Mixing causes problems with interface satisfaction:

package main
import "fmt"

type Counter struct{ n int }

func (c *Counter) Inc()   { c.n++ }   // pointer
func (c *Counter) Val() int { return c.n } // pointer too

func main() {
    c := &Counter{}
    c.Inc(); c.Inc()
    fmt.Println(c.Val()) // 2
}

Interface Satisfaction

A pointer receiver method is only in the method set of *T, not T. This affects interface satisfaction:

package main
import "fmt"

type Writer interface{ Write([]byte) }

type File struct{ name string }
func (f *File) Write(b []byte) { fmt.Println(string(b)) }

func main() {
    var w Writer = &File{"out.txt"} // OK
    // var w Writer = File{} — compile error
    w.Write([]byte("hello"))
}

Auto Address-Taking

Go automatically takes the address when calling a pointer-receiver method on an addressable value:

package main
import "fmt"

type Box struct{ V int }
func (b *Box) Double() { b.V *= 2 }

func main() {
    b := Box{5}
    b.Double()          // Go does (&b).Double()
    fmt.Println(b.V)    // 10
}

Non-Addressable Values

You cannot call pointer-receiver methods on non-addressable values (map elements, function return values not assigned to variables):

package main

type T struct{ V int }
func (t *T) Set(v int) { t.V = v }

func getT() T { return T{} }

func main() {
    var t T
    t.Set(1)       // OK — t is addressable
    // getT().Set(1) — ERROR: cannot take address of getT()
    _ = t
}

Large Struct Receivers

Always use pointer receivers for large structs to avoid expensive copies on every method call:

package main

type Image struct{ pixels [1024][1024]uint8 }

// Value receiver copies 1MB per call!
func (img Image) Bad() uint8 { return img.pixels[0][0] }

// Pointer receiver — zero copy
func (img *Image) Good() uint8 { return img.pixels[0][0] }

func main() { _ = Image{} }

Nil Pointer Receivers

Methods with pointer receivers can handle nil gracefully:

package main
import "fmt"

type List struct{ head *node }
type node struct{ val int; next *node }

func (l *List) Len() int {
    if l == nil { return 0 }
    count := 0
    for n := l.head; n != nil; n = n.next { count++ }
    return count
}

func main() {
    var l *List
    fmt.Println(l.Len()) // 0
}

Embedding and Pointer Receivers

When embedding a type with pointer receivers, the outer struct must also be used as a pointer to get the promoted methods:

package main
import "fmt"

type Base struct{ V int }
func (b *Base) Set(v int) { b.V = v }

type Derived struct{ Base }

func main() {
    d := &Derived{}
    d.Set(42)           // promoted pointer-receiver method
    fmt.Println(d.V)    // 42
}

Copying Mutexes

Never copy a struct that contains a sync.Mutex — always use a pointer receiver or pass by pointer. Copying a locked mutex results in a deadlock:

package main
import "sync"

type Safe struct {
    mu sync.Mutex
    v  int
}

// Correct: pointer receiver
func (s *Safe) Set(v int) {
    s.mu.Lock()
    defer s.mu.Unlock()
    s.v = v
}

func main() { _ = Safe{} }

go vet Detects Mistakes

Run go vet ./... to catch common pointer-receiver mistakes such as copying mutexes and locks. It's part of go build pipelines and CI checks.

Quick Check

A pointer-receiver method is in the method set of which types?

Recap

Key takeaways:

  • Pointer receivers mutate; value receivers don't
  • Keep all methods on a type using the same receiver kind
  • Only *T satisfies interfaces requiring pointer-receiver methods
  • Never copy structs with mutexes — use pointer receivers

Practice Prompt

Implement a Queue struct with pointer-receiver Enqueue(int), Dequeue() (int, bool), and Len() int methods backed by a []int slice.

Frequently asked questions

Is the “Pointer Receivers on Methods” lesson free?

Yes — the full text of “Pointer Receivers on Methods” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “Pointer Receivers on Methods”?

Mutating struct state via pointer receivers You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Pointer Receivers on Methods” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. What Are Pointers?
  2. Pointers and Functions
  3. Pointer Receivers on Methods
  4. new() and When to Use Pointers
← Back to Go Academy