Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 147 ยท Structs and Methods

Value vs Pointer Receivers

Learn when a Go method needs a pointer receiver and when a value receiver is enough - mutation, copying cost, method sets, map elements and interface satisfaction.

Every Go method has a receiver, the value the method is called on. You can declare the receiver as a plain value, func (c Counter) Value() int, or as a pointer, func (c *Counter) Increment(). The two look almost the same, but they behave very differently: a value receiver works on a copy, a pointer receiver works on the original.

Choosing between them is one of the first design decisions you make for every new type. This lesson explains exactly what each form does, when mutation or size forces your hand, the rule of thumb that keeps a type consistent, and two places where the choice shows up in surprising compile errors: calling pointer methods on map elements and satisfying interfaces. It builds directly on Methods and Pointers.

A value receiver gets a copy

Go passes everything by value, and the receiver is no exception. When you call a method with a value receiver, Go copies the value into the receiver parameter. Changes made inside the method affect only that copy:

Go Value receivers modify a copy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Both calls print inside Increment: 1, and the original stays at 0. The method incremented a throwaway copy. This is not a bug in Go; it is the same rule as for ordinary function parameters.

A pointer receiver gets the original

With a pointer receiver the method gets the address of the value, so it can change the real thing. You call it exactly the same way. Go takes the address for you when the variable is addressable:

Go Pointer receivers modify the original

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Notice two conveniences. counter.Increment() is rewritten to (&counter).Increment(), and p.Value() is rewritten to (*p).Value(). You can call either kind of method through either a value or a pointer, as long as taking the address is legal (more on that in a moment). Inside the method, c.n++ needs no explicit dereference either: field access works through a pointer automatically.

Because the call syntax is identical, you can't tell from counter.Increment() whether the method mutates. The receiver type in the method declaration is the only signal, which is why consistent choices matter.

When you must use a pointer receiver

There are two reasons to reach for a pointer receiver. The first is mutation: if the method changes the receiver, it needs a pointer, as you just saw. Setters, Add, Push, Reset and similar methods all take pointers.

The second is a type that must not be copied. Types that contain a sync.Mutex, a sync.WaitGroup or a strings.Builder break when copied, because the copy has its own lock state or buffer. Giving such a type value-receiver methods would copy the lock on every call:

Go A struct with a mutex needs pointer receivers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

wg.Go (Go 1.25) starts a goroutine and tracks it for you; the Concurrency chapter explains goroutines in detail. For now, the point is that all methods share one SafeCounter. Run go vet on a version with value receivers and it reports "passes lock by value", because the copy would have its own independent mutex.

Size is a secondary reason

A value receiver copies the whole struct on every call. For a struct of two ints that costs nothing, but for a struct with a large array field, copying can hurt:

Go
type Frame struct {
	pixels [1 << 20]byte // 1 MiB
	label  string
}

func (f Frame) Label() string { return f.label } // copies 1 MiB per call
func (f *Frame) Reset()       { f.label = "" }

Go's compiler can often avoid or inline such copies, so do not choose pointer receivers purely out of fear. But for large structs a pointer receiver is the safer default. Small, immutable values such as time.Time, image.Point or your own Point{X, Y} are good candidates for value receivers.

The consistency rule

The Go community's rule of thumb, found in Go's code review guidance, is: pick one receiver kind per type and use it for all its methods. If any method needs a pointer, make them all pointers. The reasons are practical:

  • A reader seeing *T knows the type is meant to be shared and mutated.
  • The method sets stay predictable (see below).
  • You won't get a surprise when you later add a mutating method and an older value-receiver method silently works on stale copies.

The exceptions are rare and deliberate, mostly tiny immutable types that mix a few value methods with pointer-only helpers like UnmarshalJSON. When in doubt, use pointers for structs and values for small basic types and immutable values.

Defined types over basic types follow the same rules. A slice type with an Append-style method needs a pointer receiver because appending may change the slice header:

Go Pointer receiver on a slice type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Peek only reads, so it could use a value receiver, but this is one of the deliberate mixed cases: the slice header is three words, and Peek mutates nothing. Many codebases still prefer (s *Stack) everywhere for uniformity. Both are legal.

Method sets and addressability

Here is the precise rule that governs calls and interfaces. Every type has a method set:

Type Method set contains
T methods with receiver T
*T methods with receiver T and methods with receiver *T

So *T has more methods than T. When you write x.M() on a variable x of type T and M has a pointer receiver, Go rewrites it to (&x).M(). That works only if x is addressable: a variable, a pointer dereference, a slice element, or a field of an addressable struct. Values that are not addressable, such as the result of a function call or a map element, can't have their address taken:

Go Pointer method on a non-addressable value (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler stops with cannot call pointer method Increment on Counter. The value returned by newCounter() is a temporary with no address, so there is nothing for the method to modify. Store it in a variable first, or have the function return *Counter.

Pointer methods and map elements

Map elements are not addressable either, because the map may move entries around as it grows. That produces a classic error when the map holds struct values:

Go Calling a pointer method on a map element (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler reports cannot call pointer method Deposit on Account. Assigning to a field has the same limit: accounts["ana"].balance = 15 fails with cannot assign to struct field accounts["ana"].balance in map. There are two standard fixes. Store pointers in the map, or copy the value out, change it and store it back:

Go Two fixes for struct values in maps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Slice elements, by contrast, are addressable, so accountsSlice[0].Deposit(5) works. A map of pointers is convenient but means the map's values can be nil and are shared by anything that holds the same pointer.

Interface satisfaction

The method-set table has a big consequence for interfaces (covered fully in Interfaces). A type satisfies an interface only if the interface's methods are in the type's method set. If a method has a pointer receiver, only *T satisfies the interface, not T:

Go Which type satisfies the interface (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The error reads cannot use Counter{} (value of struct type Counter) as Incrementer value in variable declaration: Counter does not implement Incrementer (method Increment has pointer receiver). This is by design: an interface variable holds a copy of the value, so calling a mutating method through it would change the copy and not your original. Go refuses rather than let that bug through. The reverse always works: a *T can use value-receiver methods, because Go can dereference the pointer.

When a compiler message mentions "has pointer receiver", the fix is almost always to pass &value instead of value.

Nil receivers

A pointer receiver can be nil, and Go calls the method anyway. That is legal and occasionally useful, as long as the method checks for it:

Go
type Node struct {
	next *Node
	val  int
}

// Len works on an empty list (a nil *Node).
func (n *Node) Len() int {
	if n == nil {
		return 0
	}
	return 1 + n.next.Len()
}

A value receiver called through a nil pointer panics, because Go must dereference the pointer to copy the value. That is one more reason to stay consistent.

Quick decision guide

Ask these questions in order:

  1. Does any method mutate the receiver? Use pointer receivers for the whole type.
  2. Does the struct contain a mutex, a WaitGroup, a Builder, or anything else that must not be copied? Pointer receivers.
  3. Is the struct big, or does it contain large arrays? Pointer receivers.
  4. Is it a small immutable value (a point, a color, a timestamp) or a basic type like type Celsius float64? Value receivers.
  5. Not sure? Pointer receivers; they are rarely wrong for structs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A method is declared func (c Counter) Increment() { c.n++ }. After calling it twice on var x Counter, what is x.n?

    A value receiver is a copy, so the increment changes only the copy. The original stays at 0.
  2. 2. Which statement about method sets is correct?

    A pointer can always be dereferenced to call value-receiver methods, so *T has both kinds. T only has value-receiver methods.
  3. 3. Why does accounts["ana"].Deposit(5) fail when Deposit has a pointer receiver and accounts is map[string]Account?

    Go can't take the address of a map element because the map may relocate entries, so it can't call a pointer method on it. Store pointers or copy, modify and store back.
  4. 4. A type has func (c *Counter) Increment(). Which assignment compiles?

    Only *Counter has Increment in its method set, so only &Counter{} satisfies the interface.
  5. 5. Which type should normally have pointer receivers?

    Copying a mutex copies its lock state and breaks mutual exclusion, so such types must be used through pointers.

Summary

  • A value receiver works on a copy; a pointer receiver works on the original and can mutate it.
  • Go rewrites x.M() to (&x).M() and p.M() to (*p).M() when the value is addressable.
  • Use pointer receivers when methods mutate, when the type holds a mutex or other uncopyable state, or when it is large.
  • Pick one receiver kind per type and use it for every method.
  • The method set of T has only value-receiver methods; the method set of *T has both.
  • Function results and map elements are not addressable, so pointer methods can't be called on them directly.
  • A type with pointer-receiver methods satisfies an interface only as *T, not as T.

Next: Struct Embedding and Composition