0PricingLogin
Go Academy · Lesson

Pointer Receivers on Methods

Mutating struct state via pointer receivers

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
}

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