Andrew's Digital Garden

Receivers in Go

Receivers in Go turn a function into a method, allowing it to be called on a struct or similar (similar to a class). Receivers can be a pointer, or a value. In general, all methods on a given type should have either value or pointer receivers, but not a mixture of both. Receivers are expected to modify and return (different from FP) - thus, use a pointer receiver when in doubt. Pointer receivers also have the added benefit of better memory usage, as large values dont need to be copied.

Without a receiver:

type Vertex struct { X, Y float64 } func Abs(v Vertex) float64 { return math.Sqrt(v.X*v.X + v.Y*v.Y) } func main() { v := Vertex{3, 4} fmt.Println(Abs(v)) }

With a receiver:

type Vertex struct { X, Y float64 } func (v Vertex) Abs() float64 { return math.Sqrt(v.X*v.X + v.Y*v.Y) } func main() { v := Vertex{3, 4} fmt.Println(v.Abs()) }

[[go]]

Receivers in Go