liveBook · Manning

Receiver

As explained in 100 Go Mistakes and How to Avoid Them

A receiver is the parameter of a Go method that identifies the value or pointer on which the method operates.

A receiver is the value or pointer attached to a Go method. Choosing the wrong kind can make a mutation appear to succeed while leaving the original value unchanged. section 6.0 section 6.1

Choose the receiver according to the operation and the value being handled:

  • Use a value receiver when the method should operate on a copy; mutations remain local and the original value is unchanged. section 6.1
  • Use a pointer receiver when the method must mutate the original object; the method receives a copied pointer to that object. section 6.1
  • A pointer receiver is required when appending through a slice receiver or when the receiver contains a value that cannot be copied. section 6.1
  • A pointer receiver is generally preferable for large objects, but benchmark when size makes the choice uncertain. section 6.1

The mutation that disappears

With `func (c customer) add(v float64)`, a customer starting at 100.00 still prints 100.00 after `c.add(50.)`. Changing the declaration to `func (c *customer) add(v float64)` makes it print 150.00. A value receiver copies the customer; a pointer receiver updates the original.

Deferred methods evaluate receivers immediately

In `defer s.print()`, Go evaluates the receiver when the defer statement runs. A value receiver captures the current struct, so changing `s.id` from `foo` to `bar` still prints `foo`. A pointer receiver observes the later change and prints `bar`. section 6.6.2

type slice []int
 
func (s *slice) add(element int) {
    *s = append(*s, element)
}

A slice receiver uses a pointer so that appending can replace the slice value held by the receiver. section 6.1

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains copying, mutation, deferred evaluation, and selection conditions while deferring thorough value-versus-pointer performance treatment.
Examples
Uses customer balances, slice appending, nested pointer data, and deferred printing to expose receiver behavior.
What it assumes
Assumes familiarity with Go functions and methods while refreshing how methods attach to receiver values or pointers.
What you can do after
Apply it by selecting value or pointer receivers based on mutation, copying constraints, receiver size, and deferred-call behavior.
How it connects
Connects receivers with methods, pointers, values, slices, mutation, copying, and defer evaluation.

Also explained in

Compare how 3 books explain receiver →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.