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
- What Are Pointers?
- Pointers and Functions
- Pointer Receivers on Methods
- new() and When to Use Pointers