Pointer receiver (*T) — method gets a pointer to the value, can modify the original, avoids copying. Value receiver (T) — method gets a copy, changes don't affect the original.
The receiver type determines whether the method has side effects. Pointer receivers are the only way to mutate the receiver's state from within a method.
1type TreeNode struct {2 Value int3 Left *TreeNode4 Right *TreeNode5}67// Pointer receiver — modifies the tree8func (n *TreeNode) Insert(val int) {9 if val < n.Value {10 if n.Left == nil {11 n.Left = &TreeNode{Value: val}12 } else {13 n.Left.Insert(val)14 }15 } else {16 if n.Right == nil {17 n.Right = &TreeNode{Value: val}18 } else {19 n.Right.Insert(val)20 }21 }22}
When to use:
Common mistakes: