Go methods
A Go function can be defined with a scope narrowed to that of a specific type. When a function is scoped to a type, or attached to the type, it is known as a method. A method is defined just like any other Go function. However, its definition includes a method receiver, which is an extra parameter placed before the method's name, used to specify the host type to which the method is attached.
To better illustrate this concept, the following figure highlights the different parts involved in defining a method. It shows the quart
method attached to the type gallon
based receiver via the g gallon
receiver parameter:
As mentioned, a method has the scope of a type. Therefore, it can only be accessed via a declared value (concrete or pointer) of the attached type using dot notation. The following program shows how the declared method quart
is accessed using this notation:
package main import "fmt" type gallon float64 func (g gallon) quart() float64 { ...