liveBook · Manning

Pointer receiver

As explained in Learn Go with Pocket-Sized Projects

A pointer receiver is a method receiver whose parameter points to the receiver value, allowing method operations to access the original value.

A pointer receiver attaches a method to a pointer to a struct value. The declaration `func (g *Game) Play()` lets `Play` operate through the `Game` pointer returned by `New`. section 5.1.1

Use pointer receivers consistently for a type rather than mixing pointer and value receivers. Value receivers are mainly useful for structures that are small in memory; pointer receivers are also required when an operation such as `simplify` needs pointer access. section 5.6 section 6.4.3

Running a game through a pointer receiver

A constructor returns a pointer, and the caller invokes the pointer-receiver method directly:\n\n`func New() *Game {\n g := &Game{}\n return g\n}`\n\n`func (g *Game) Play() {\n fmt.Println("Welcome to Gordle!")\n}`\n\n`g := gordle.New()`\n`g.Play()` section 5.1.1

Listing 5.3 game.go: Using Play to run the game
// Play runs the game.
func (g *Game) Play() {
    fmt.Println("Welcome to Gordle!")

    fmt.Printf("Enter a guess:\n")
}

Inspect the complete `Play` method declaration and its terminal output. section 5.1.1

Listing 6.30 decimal.go: Implementing the Decimal Stringer
// String implements stringer and returns the Decimal formatted as
// digits and optionally a decimal point followed by digits.
func (d *Decimal) String() string {
    // Quick-win, no need to do maths.
    if d.precision == 0 {
        return fmt.Sprintf("%d", d.subunits) #1
    }

    centsPerUnit := pow10(d.precision) #2
    frac := d.subunits % centsPerUnit
    integer := d.subunits / centsPerUnit

    decimalFormat := "%d.%0" + #3
        strconv.Itoa(int(d.precision)) + "d"  #3
    return fmt.Sprintf(decimalFormat, integer, frac)

}

Compare a pointer receiver used to implement formatted output for `Decimal`. section 6.4.3

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines receiver syntax, demonstrates invocation, and gives consistency guidance without detailing method-set internals.
Examples
Uses a terminal word game’s `Game.Play` method and a currency converter’s `Decimal.String` implementation.
What you can do after
Build it from scratch by declaring pointer-receiver methods and calling them on constructor-returned pointers.
How it connects
Connects methods with structs, constructors, value receivers, and interface implementation.

Also explained in

Compare how 2 books explain pointer 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.