Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Go Methods: Value vs Pointer Receivers, Method Sets, and Expressions

Value and pointer receivers, the method sets they produce, why map elements cannot call pointer methods, and method values that capture a copy.

~5 min readGo
#Go#Methods#OOP
3D illustration of struct method calls contrasting pointer mutations against isolated copied value blocks

A method is a function with a receiver, and the receiver's form decides two things that are easy to conflate: whether the method can modify the original value, and whether the type satisfies an interface. A value receiver gets a copy, so mutations are lost; a pointer receiver shares the original, so mutations stick. The method set — the set of methods callable on a type — then determines interface satisfaction, and it differs between T and *T in exactly one direction: *T has every method, T has only the value-receiver ones.

Quick Summary

  • func (t T) M() copies the receiver; func (t *T) M() receives the address and can mutate.
  • The method set of *T includes methods with either receiver; the method set of T includes only value receivers.
  • So *T can satisfy an interface that T cannot, and that is the most common source of method has pointer receiver errors.
  • v.M() with a pointer receiver compiles when v is addressable: the compiler rewrites it to (&v).M().
  • Map elements, function return values, and interface values are not addressable, so pointer-receiver methods cannot be called on them.
  • t.M as a value binds a copy of the receiver at that moment; it does not read the receiver again when called.
  • T.M as an expression is a plain function taking the receiver as its first argument.
  • Once any method needs a pointer receiver, give the type pointer receivers throughout, or the type and its pointer will have different method sets and behave differently in interfaces.

Basic syntax and type signatures

go
type Counter struct { n int } func (c Counter) Value() int { return c.n } // copy func (c *Counter) Inc() { c.n++ } // mutates the original func (c *Counter) Reset() { c.n = 0 } func use() { var c Counter c.Inc() // (&c).Inc() c.Inc() fmt.Println(c.Value(), c.n) // 2 2 p := &c p.Inc() // no rewrite needed fmt.Println(p.n) // 3 }
go
// Method expression: receiver becomes the first parameter. inc := (*Counter).Inc // func(*Counter) inc(&c) val := Counter.Value // func(Counter) int fmt.Println(val(c)) // works on a copy // Method value: receiver bound now. get := c.Value // func() int, bound to a copy of c at this moment c.Inc() fmt.Println(get(), c.Value()) // 3 4 — the bound copy did not change

Receivers must be declared in the same package as the type, and the type must be a defined type, not a pointer or an interface:

go
type MyInt int func (m MyInt) Double() MyInt { return m * 2 } // ok // func (s string) Len() int { ... } // cannot define new methods on non-local type string // type Alias = MyInt // func (a Alias) X() {} // invalid receiver type Alias (alias, not defined type)

Comparison of receiver forms

Aspectfunc (t T)func (t *T)
Receiver contentscopy of the valuepointer to the value
Mutations visible to callernoyes
Method in method set of Tyesno
Method in method set of *Tyesyes
Callable on a non-addressable valueyesno (compile error)
Nil receiver allowedn/ayes, if the method checks for nil
Cost per callcopy of the valuepointer copy
Safe to copy in go vet termsyesthe receiver itself is a pointer, the pointee may hold a lock
Typical usesmall immutable values, string-like typesstructs with state, locks, large values

The rule of thumb: if any method mutates, all methods take pointers; if the type is a small immutable value (a wrapper around a number, an error type, a time.Time-like struct), value receivers are simpler and avoid nil handling. Mixing the two on one type is legal and is where interface surprises come from.

Practical edge cases and deep dives

1. Value receivers copy, including the parts that look like references

go
type Buffer struct { data []byte n int } func (b Buffer) Append(p []byte) { // value receiver b.data = append(b.data, p...) // reassigns the copy's slice header b.n += len(p) // lost } func (b Buffer) MutateFirst() { if len(b.data) > 0 { b.data[0] = 'X' // visible: the backing array is shared } } func (b *Buffer) AppendFixed(p []byte) { b.data = append(b.data, p...) b.n += len(p) } b := Buffer{data: make([]byte, 0, 10)} b.Append([]byte("hi")) fmt.Println(len(b.data), b.n) // 0 0 — the header reassignment was lost b.AppendFixed([]byte("hi")) fmt.Println(len(b.data), b.n) // 2 2

A slice is a three-word header, and copying the struct copies the header while sharing the backing array. That produces the most confusing class of value-receiver bug: MutateFirst visibly changes the caller's data, so the receiver "obviously" shares state, and then Append silently loses the length. Whether a value-receiver method can mutate depends on which part of the value is a reference — a rule worth avoiding by using pointer receivers for anything mutable.

2. Method sets and interface satisfaction

go
type Speaker interface { Speak() string } type Dog struct{ name string } func (d Dog) Speak() string { return d.name + ": woof" } func (d *Dog) Rename(n string) { d.name = n } var _ Speaker = Dog{} // ok: Speak has a value receiver var _ Speaker = &Dog{} // ok: *Dog's method set includes it type Cat struct{ name string } func (c *Cat) Speak() string { return c.name + ": meow" } // var _ Speaker = Cat{} // compile error: Cat does not implement Speaker // // (method Speak has pointer receiver) var _ Speaker = &Cat{} // ok

The error text is cannot use Cat{} (variable of type Cat) as Speaker value in variable declaration: Cat does not implement Speaker (method Speak has pointer receiver). It appears whenever a value is stored in an interface and the method needs a pointer — including a function parameter of interface type, a slice of interfaces, and a map value of interface type. Storing &Cat{} fixes it, and the fix is a real decision: the interface now holds a pointer, so a copy of the interface shares the Cat.

The consequence shows up in constructors that return interfaces:

go
func NewCat(name string) Speaker { return &Cat{name: name} // returning Cat would not compile }

3. Non-addressable receivers: map elements and return values

go
type Item struct{ Count int } func (i *Item) Inc() { i.Count++ } m := map[string]Item{"a": {}} // m["a"].Inc() // compile error: cannot call pointer method Inc on Item value m["a"] items := []Item{{}, {}} items[0].Inc() // ok: slice elements are addressable fmt.Println(items[0].Count) // 1 func makeItem() Item { return Item{} } // makeItem().Inc() // compile error: cannot call pointer method on makeItem() ptrMap := map[string]*Item{"a": {}} ptrMap["a"].Inc() // ok: the map value is a pointer, and the pointee is addressable fmt.Println(ptrMap["a"].Count) // 1

A map element is not addressable because the map may rehash and move it, so &m[k] is not allowed and neither is the implicit & of a pointer-receiver call. The workarounds are a map of pointers (usually the right one when the elements are mutable), a read-modify-write (it := m["a"]; it.Inc(); m["a"] = it), or a map of a small value type with value-receiver methods that return the modified copy.

4. Method values capture the receiver at evaluation time

go
type Logger struct{ prefix string } func (l Logger) Log(msg string) { fmt.Println(l.prefix, msg) } func (l *Logger) SetPrefix(p string) { l.prefix = p } l := Logger{prefix: "v1"} f := l.Log // bound to a COPY of l l.SetPrefix("v2") f("hello") // prints "v1 hello" g := l.Log // new binding, now "v2" g("hello") // prints "v2 hello" // The classic loop bug with method values: var fns []func() for i := 0; i < 3; i++ { l := Logger{prefix: fmt.Sprint(i)} fns = append(fns, l.Log) // each closure holds its own copy } for _, fn := range fns { fn("x") } // 0 x, 1 x, 2 x

A method value on a pointer receiver binds the pointer, so changes through that pointer are visible; a method value on a value receiver binds a copy, so later mutations are invisible. Both behaviors are useful and both are invisible at the call site, which is why passing obj.Method as a callback deserves a second look when the object is mutable.

5. Nil receivers, String(), and copied locks

go
type List struct { head *node size int } func (l *List) Len() int { if l == nil { return 0 } return l.size } var nilList *List fmt.Println(nilList.Len()) // 0: calling a method on a nil pointer is legal type Config struct{ path string } func (c *Config) String() string { return c.path } cfg := Config{path: "/etc"} fmt.Println(cfg) // {/etc} — not "/etc": String has a pointer receiver fmt.Println(&cfg) // /etc type Service struct { mu sync.Mutex n int } func (s Service) Bad() {} // go vet: Bad passes lock by value func (s *Service) Good() {}

fmt receives its argument as an interface; a Config value's method set does not include String(), so the formatter falls back to the struct's default formatting, while &cfg does implement it. That single asymmetry explains most "my String() method is ignored" reports. The go vet check on a value receiver of a struct containing a sync.Mutex is the same problem from the other direction: the copy is a second, independent lock over shared state, and the protection quietly stops working.

Common mistakes and compiler errors

Error or symptomCauseFix
cannot use t (variable of type T) as I value: T does not implement I (method M has pointer receiver)method set of T lacks pointer methodspass &t, or switch the method to a value receiver
cannot call pointer method M on Treceiver not addressable (map element, call result)store pointers, or copy out and back
cannot take the address of m[k]map elements are not addressableuse a pointer map
Mutation in a value-receiver method has no effectreceiver is a copypointer receiver
Mutation partly works for slices/mapsthe copy shares the backing arraypointer receiver for anything mutable
A String()/Error() method is ignoredpointer receiver, value passed to fmt or errordefine it on the value receiver, or pass the pointer
go vet: passes lock by valuevalue receiver copies a struct containing a mutexpointer receiver
Method value sees stale fieldsreceiver copy captured at evaluationbind the pointer, or call the method directly
Loop callbacks all use the last valueshared variable captureddeclare a per-iteration variable
invalid receiver typereceiver is a pointer alias or an interfaceuse a defined type in the same package

The design decision is worth making once per type rather than per method. If the type holds state that any method changes, or contains a lock, a map, a slice, or a channel, use pointer receivers everywhere and construct with &T{...}; the method set then matches the type's actual semantics, interfaces work with a single form, and no caller has to wonder whether a copy is happening. Reserve value receivers for small values that are conceptually immutable — a Money amount, a coordinate, an error value — where a copy is exactly what you want and T satisfying the interface is a feature rather than a trap.

Try matching browser tools

All tools

Small utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Go guides

More in Go

All Go guides

The guides filed next to this one in Go, in library order.