The Analogy: The Machine's Own Control Panel
There are two ways to run a workshop. In the first, procedures live in a binder: you look up "shut down the lathe", find the page, and it tells you which machine to apply it to. In the second, every machine carries its own panel, and the shutdown button is bolted to the lathe. The button does exactly what the binder page did — but it cannot be pressed on the wrong machine, you find it by walking up to the lathe rather than by searching an index, and the drill press is free to have a shutdown button of its own that works completely differently.
A Go method is the button. r.Close() is mechanically the same as Close(r) with the argument moved in front of the name, and the compiler treats it as such. What you buy is namespacing and discoverability: every type in your program may have its own Close, String or Len without collision, go doc lists a type's methods next to the type, and an editor can complete them after you type the dot. Nothing more mysterious than that is going on.
Because the receiver is a parameter, every parameter rule from two lessons ago still applies — above all that arguments are copied. A method declared func (c Counter) Peek() int receives its own Counter, so anything it writes to c is discarded when it returns. A method declared func (c *Counter) Inc() receives the address instead, and writes land on the caller's value. Choosing between those two for each type is the single most consequential decision in this lesson, and getting it wrong produces code that works partially, which is worse than code that fails.
Go then hides the distinction at the call site, on purpose. If c is a variable, c.Inc() compiles even though Inc wants a *Counter, because the compiler inserts the & for you; likewise p.Peek() on a pointer inserts the *. Convenient, and the reason the pointer-versus-value question is so easy to overlook — the sugar only stops working in the places where there is nothing to take the address of, such as a map element, and in the method set rules that decide which interfaces your type satisfies. That last point is the bridge to the next lesson.
Syntax or Core Structure
A method on a non-struct type, both receiver forms on one struct, the automatic address-of, and method values versus method expressions.
package main
import "fmt"
// Methods work on any defined type you declare, not only on structs.
type Meter float64
func (m Meter) Feet() float64 { return float64(m) * 3.28084 }
type Counter struct{ n int }
func (c Counter) Peek() int { return c.n } // gets a copy
func (c *Counter) Inc() int { c.n++; return c.n } // gets the address
func main() {
var m Meter = 100
fmt.Printf("%.1f m = %.2f ft\n", float64(m), m.Feet())
c := Counter{}
c.Inc() // the compiler writes (&c).Inc() for you
c.Inc()
fmt.Println("peek:", c.Peek())
// A copy is a different machine.
copyOf := c
copyOf.Inc()
fmt.Println("original:", c.Peek(), "copy:", copyOf.Peek())
// Through a pointer both forms work: Peek gets an automatic *.
p := &c
p.Inc()
fmt.Println("via pointer:", p.Peek())
inc := p.Inc // method value: receiver bound now
fmt.Println("bound call:", inc())
peek := Counter.Peek // method expression: receiver is the first argument
fmt.Println("expression:", peek(c))
// counters := map[string]Counter{"a": {}}
// counters["a"].Inc() // will NOT compile: map elements are not addressable
counters := map[string]*Counter{"a": {}}
counters["a"].Inc()
fmt.Println("map:", counters["a"].Peek())
}
Output:
100.0 m = 328.08 ft
peek: 2
original: 2 copy: 3
via pointer: 3
bound call: 4
expression: 4
map: 1
The commented-out lines are the important ones. counters["a"].Inc() on a map[string]Counter fails because calling a pointer-receiver method requires taking the receiver's address, and a map element has no address — the same rule from the pointers lesson, arriving through a different door. Storing *Counter in the map sidesteps it entirely, which is why maps of mutable values are almost always maps of pointers.
Technical Depth: Receivers, Method Sets and the Sugar's Limits
What may be a receiver
| Receiver | Legal | Why |
|---|---|---|
func (t T) or func (t *T) where T is declared in this package | Yes | The normal case. T may be a struct, a slice type, a map type, a number, a string — anything you defined. |
A type from another package (func (t time.Time)) | No | You cannot add methods to somebody else's type. Define your own type over it, or embed it. |
| An interface type | No | Interfaces declare methods; they do not carry implementations. |
A pointer to a pointer (**T) | No | Exactly one level of indirection is allowed. |
An unnamed type (func (s []int)) | No | Declare type IntSlice []int first. |
| Two receivers | No | One receiver, and it goes before the name. |
A method must also live in the same package as its receiver type, and its name must not collide with a field name on the same struct.
Choosing the receiver
| Use a pointer receiver when | Use a value receiver when |
|---|---|
| The method mutates the receiver | The type is small and the method only reads |
| The struct is large enough that copying it costs | The type is a number, string or small struct where a copy is cheaper than an indirection |
The type contains a sync.Mutex, a sync.WaitGroup or anything else that must not be copied | You want the method available on both T and *T in interface satisfaction |
| Any other method on the type already needs one | Every method on the type is read-only |
The last row of the left column is the rule that matters in practice: be consistent per type. A type with nine pointer receivers and one value receiver is a bug waiting for someone to call the tenth method on a copy.
Method sets, and why they decide interface satisfaction
| Declared as | In T's method set | In *T's method set |
|---|---|---|
func (t T) Read() | Yes | Yes |
func (t *T) Write() | No | Yes |
Read that asymmetry twice, because it produces the most common compile error in Go. If Write has a pointer receiver, then T does not implement an interface requiring Write — only *T does — so you must pass &v, not v. The reason is precisely the addressability rule: the language can guarantee it is able to take the address of a variable, but not of every value that might be stored in an interface.
Where the automatic & and * stop working
| Expression | Pointer-receiver call allowed |
|---|---|
v.M() on a local variable, field, slice or array element | Yes — &v is inserted |
p.M() on a *T | Yes, natively |
m["k"].M() on a map[string]T | No. Not addressable. |
f().M() on a function returning T | No. Not addressable. |
i.M() where i is an interface holding a T | No. The value inside an interface is not addressable, which is the method-set rule in disguise. |
T{}.M() on a composite literal | No — but (&T{}).M() is fine. |
The nil pointer receiver
A pointer-receiver method can be called on a nil pointer and only panics if it dereferences. Handling nil deliberately is a real technique: it lets (*Tree).Insert treat the empty tree as a normal case, and it lets a String method render an absent value instead of crashing the log line that printed it.
Promoted methods see the inner type, not the outer one
Embedding promotes methods, but the promoted method's receiver is still the embedded value. It cannot see the outer struct's fields and it cannot be overridden — if the inner method calls another of its own methods, it calls the inner one even when the outer type has declared a replacement. This is delegation, and the next lesson explains what to use when you wanted dispatch.
The String recursion trap
func (c Cents) String() string {
return fmt.Sprintf("%v", c) // infinite recursion: %v calls String again
}
fmt consults String for %v, %s and %q, so formatting the receiver with any of those verbs from inside String recurses until the stack is exhausted — and a stack overflow cannot be recovered. Convert first: fmt.Sprintf("%d", int64(c)). go vet catches the direct case and misses it once a helper function is involved.
Real World Example: The Receiver Bug That Half Works
Two tallies with identical call sites. One has a value receiver, and the result is code that passes half of its tests.
package main
import (
"fmt"
"sort"
)
// Broken on purpose: Add receives a copy of the struct.
type BadTally struct {
counts map[string]int
total int
}
func (b BadTally) Add(k string) {
b.counts[k]++ // survives: the map field is a handle to shared state
b.total++ // lost: total is an int inside the copy
}
type Tally struct {
counts map[string]int
total int
}
// The zero value would panic on a nil map write, so construction is required.
func NewTally() *Tally { return &Tally{counts: map[string]int{}} }
func (t *Tally) Add(k string) {
t.counts[k]++
t.total++
}
func (t *Tally) Top() (string, int) {
keys := make([]string, 0, len(t.counts))
for k := range t.counts {
keys = append(keys, k)
}
sort.Strings(keys) // ties must resolve the same way on every run
best, n := "", -1
for _, k := range keys {
if t.counts[k] > n {
best, n = k, t.counts[k]
}
}
return best, n
}
// Declared on *Tally, so only *Tally is a fmt.Stringer.
func (t *Tally) String() string {
if t == nil {
return "tally(nil)"
}
top, n := t.Top()
return fmt.Sprintf("tally(total=%d distinct=%d top=%s x%d)",
t.total, len(t.counts), top, n)
}
func main() {
words := []string{"go", "is", "go", "fun", "go", "is"}
bad := BadTally{counts: map[string]int{}}
for _, w := range words {
bad.Add(w) // looks identical to the correct version below
}
fmt.Println("bad total:", bad.total, "distinct:", len(bad.counts),
"go:", bad.counts["go"])
good := NewTally()
for _, w := range words {
good.Add(w)
}
fmt.Println("good total:", good.total, "distinct:", len(good.counts),
"go:", good.counts["go"])
// %v finds String because good is a *Tally.
fmt.Printf("stringer: %v\n", good)
// A nil *Tally formats fine, because the method checks for it.
var missing *Tally
fmt.Printf("nil: %v\n", missing)
top, n := good.Top()
fmt.Printf("top: %s x%d\n", top, n)
}
Output:
bad total: 0 distinct: 3 go: 3
good total: 6 distinct: 3 go: 3
stringer: tally(total=6 distinct=3 top=go x3)
nil: tally(nil)
top: go x3
BadTally is the interesting failure because it is not a clean one. Every Add received a copy of the struct, so b.total++ incremented a field that was discarded a nanosecond later — but b.counts[k]++ worked perfectly, because the copy's counts field is a handle onto the same hash table. Distinct words: correct. Per-word counts: correct. Total: zero. A test that asserts on the counts passes, the bug ships, and the dashboard shows no traffic while the breakdown looks healthy.
The call sites give nothing away. bad.Add(w) and good.Add(w) are the same six characters, because Go inserted the & for one of them and not the other, silently and by design. No compiler warning exists for this and go vet does not look for it. The defence is the consistency rule, applied at the type rather than the method: decide once that Tally is a pointer type, give every method a pointer receiver, and return *Tally from the constructor so callers never hold a value in the first place.
String is declared on *Tally, so *Tally implements fmt.Stringer and Tally does not: fmt.Println(good) uses it and fmt.Println(*good) prints the raw struct instead. That is the method-set asymmetry showing up in the most ordinary code imaginable. The nil check earns its keep too — fmt calls String on the nil pointer, and without the guard the method would dereference t and panic inside a log statement, which is a spectacularly annoying way to lose a diagnostic. Note also what the method does not do: it formats t.total with %d, never %v on the receiver, because that would call String again and recurse until the stack died.
NewTally exists for one honest reason: the zero Tally has a nil counts map, and writing to a nil map panics. That is a direct conflict with the "make the zero value useful" advice from the structs lesson, and the resolution is to pick a side and document it — either lazily initialise the map inside Add so var t Tally works, or require the constructor and say so in the type's doc comment. What you must not do is leave it ambiguous, because Tally{} compiles and then panics on first use.
Common Mistakes
- A value receiver on a mutating method. The change lands on a copy. When the struct also has a map or slice field, part of the mutation survives and the bug becomes very hard to see.
- Mixing receiver styles on one type. Nine pointer receivers and one value receiver means one method behaves differently for no visible reason. Pick one per type.
- Expecting
Tto satisfy an interface implemented with pointer receivers.var w io.Writer = myBuffails where&myBufsucceeds. The error message names the method and says it "has pointer receiver".
- Calling a mutating method on a map element.
m["k"].Inc()will not compile formap[string]T. Store pointers, or read the value out, modify it, and write it back.
- Mutating the range variable and expecting the container to change.
for _, item := range items { item.Update() }callsUpdateon a fresh copy each iteration. Useitems[i].Update().
fmt.Sprintf("%v", receiver)insideString. Infinite recursion, then a stack overflow that norecovercan catch. Convert the receiver to its underlying type first.
- A value receiver on a type containing a mutex. Every call copies the lock, so the mutual exclusion quietly does nothing.
go vet'scopylockscheck finds most instances.
- Trying to add a method to a type you do not own.
func (t time.Time) Pretty() stringdoes not compile. Wrap it:type Stamp struct{ time.Time }, or take it as a parameter.
- Assuming an embedded method can be overridden. Declaring a method with the same name on the outer type shadows it for outside callers only; code inside the embedded type keeps calling its own version.
- Naming a method the same as a field.
Name stringandfunc (p Person) Name() stringon the same struct is a compile error, not an overload.
- Writing a constructor whose type also has a usable zero value. It forces every caller through your function for no benefit, and it makes the type awkward to embed. Only require construction when the zero value would misbehave.
Best Practices
- Choose the receiver per type, not per method, and write it down in the type's doc comment when the answer is "pointer, always".
- Return
*Tfrom a constructor for types that must not be copied, so callers never accidentally hold a value.
- Give a type either a usable zero value or a mandatory constructor, and document which. Ambiguity here produces panics on first use.
- Guard
Stringand other formatting methods against a nil receiver. They run inside log statements, where a panic is at its least welcome.
- Define methods on defined types over primitives —
Meter,Cents,UserID— when the formatting or validation is worth naming.
- Keep methods short and name them for what the caller wants, not for how they work.
TopbeatsComputeMaximumFromSortedKeys.
- Use a method value when passing a bound operation and a method expression when the receiver varies per call. Both beat wrapping the call in a fresh literal.
- Run
go vetin CI forcopylocksand theStringrecursion check. They cover two of the three receiver bugs that actually reach production.
Practice Exercises
- Write a
Rectstruct withArea(value receiver) andScale(pointer receiver). Call both on a variable, then on a*Rect, then on an element of a[]Rect, and finally on an element of amap[string]Rect. Record which one fails to compile and quote the error.
- Define
type Temp float64with aStringmethod rendering one decimal place and aCsuffix. Deliberately implement it asfmt.Sprintf("%v C", t)first, observe what happens, then fix it and explain the mechanism in a comment.
- Build a
Stacktype withPush,PopandLen. ImplementPushwith a value receiver on purpose, write a test that pushes three items and assertsLen() == 3, and describe exactly why it fails. Then fix the receiver and check whether any other method needed changing.
- Take the
Tallyexample and make the zero value usable: removeNewTallyand haveAddcreate the map on first use. Then list two things this design makes easier and one thing it makes harder, including what happens if two goroutines callAddat the same moment.