Receiver Methods

Reciever methods are functions with a receiver argument.


Demo

The Distance() function is implemented as a receiver method for the Point struct here.

import (
    "math"
)

type Point struct {
    x int
    y int
}

func (p Point) Distance() int {
    return math.Sqrt(math.Pow(p.x, 2) + math.Pow(p.y, 2))
}

my := Point{1, 2}
euclidean := my.Distance()

}}}

This is entirely equivalent to implementing Distance() as a function that takes a Point as an argument, as in:

func Distance(p Point) int {
    return math.Sqrt(math.Pow(p.x, 2) + math.Pow(p.y, 2))
}

my := Point{1, 2}
euclidean := Distance(my)


Definition

Receiver methods are entirely defined by the existance of a receiver type. They otherwise perform exactly as functions.

Receiver methods also can be implemented on any type, not just structs.

type Celsius int

type Fahrenheit int

func (c Celsius) Convert() Fahrenheit {
    return c * 9 / 5 + 32
}


Receiver methods and pointers

Receiver methods can be called on pointers to an object directly.

another := &my

euclidean := another.Distance()

The same not be done with a normal function.

another := &my

euclidean := Distance(*another)

The dereference is automatically inferred for receiver methods.


Pointer receiver methods

Receiver pointers are an especially useful pattern because they enable mutation of the receiver.

func (p *Point) Scale(factor int) {
    p.x = p.x * factor  p.y = p.y * factor
}

p.Scale(5)

This is entirely equivalent to:

func Scale(p *Point, factor int) {
    p.x = p.x * factor  p.y = p.y * factor
}

Scale(&p, 5)

Note that the method did not need to be called as (&p).Scale(5). The reference is automatically inferred.


CategoryRicottone

Go/ReceiverMethods (last edited 2024-03-17 15:09:00 by DominicRicottone)