liveBook · Manning

Value receiver

As explained in Learn Go with Pocket-Sized Projects

A value receiver is a method receiver passed as a value, so invoking the method operates on a copy of the receiver.

A value receiver is a method receiver passed as a value, so the method operates on a copy of the receiver rather than the original structure. section 5.6

Use value receivers selectively:

  • Choose them mainly for structures that are small in memory, because each method call copies the receiver. section 5.6
  • Keep a type's methods consistently pointer-based or value-based instead of mixing receiver kinds. section 5.6 section 5.1.2
  • Prefer a pointer receiver when methods modify state, or when the structure contains pointer fields whose behavior requires care. section 5.1.2

The Game receiver

The terminal word game uses pointer receivers for Game because several methods modify game state and Game contains an output pointer field. This keeps its receiver declarations consistent and avoids the problems associated with value receivers and pointer fields. section 5.1.2

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains copying, structure size, consistency, and pointer-field concerns, but defers detailed pointer-field behavior.
Examples
Uses the Game type, its mutable state, and its output pointer field to motivate pointer receivers instead.
What it assumes
Assumes familiarity with Go methods, structures, receivers, and pointers.
What you can do after
Apply via Go by selecting value receivers for small structures and pointer receivers when mutation or pointer fields make copying unsuitable.
How it connects
Connects value receivers with pointer receivers, methods, structures, mutable state, and pointer fields.

Also explained in

Compare how 3 books explain value receiver →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.