Golang method receiver

Victor Yeo
1 min readJan 16, 2021

--

Method receiver is a golang feature that defines the object instance where the method accesses or modifies the value. Basically, a method is a function that has a defined receiver. The method receiver appears between the func keyword and the method name.

There are two type of method receiver: value receiver and pointer receiver.

package mainimport (
“fmt”
“math”
)
type Area struct {
X, Y float64
}
func (ar Area) Abs() float64 {
return math.Sqrt(ar.X*ar.X + ar.Y*ar.Y)
}
func (ar *Area) Scale(f float64) {
ar.X = ar.X * f
ar.Y = ar.Y * f
}
func main() {
v := Area{3, 4}
v.Scale(10)
fmt.Println(v.Abs())
}

Methods with pointer receivers can modify the value to which the receiver points (as Scale does here). Since methods often need to modify their receiver, pointer receivers are more common than value receivers.

With a value receiver, the Abs method operates on a copy of the original Area value. The Scale method must have a pointer receiver to change the Area value declared in the main function.

--

--

No responses yet