What the heck are Receiver functions in Golang?

Aditya Agarwal
2 min readJan 12, 2018

Go is very similar to C due to presence of pointers, static typing and many other things. But Go is a modern language and so it has many new features baked in it.

One notable feature is receiver functions.

Let’s see some code to understand what I’m talking about.

If you notice the print function, it is a little unusual. Unlike other languages, in go we have a parameter list before the function name.

This parameter (p of type person in the example) is what makes the print() function a receiver function. More precisely, the print() function is a function which can receive a person.

This has an interesting application. Notice that we make an alex variable of type person. As print() function can receive a person, we can do alex.print().

In other programming languages, print() function is called a method. In OOPS languages like C++, Java, Python methods are available to classes.

class Car():  def __init__(self):
self.x = 0
def move(self):
self.x += 10
c = Car()
c.move()

In this python example, move is a method of class Car . All the instances of class Car like c has access to move method.All the properties of c are passed to self argument automatically (this in Java).

Go is not OOPS based, and thank god for that. OOPs was a wonderful concept but got obfuscated by these languages.

With receiver functions you don’t have to mess around with classes or deal with inheritance. The person type has no knowledge of the receiver function. One advantage of using receiver function is when we couple it with iterfaces. I hope to write about interfaces shortly. In a nutshell, by using interfaces we can use the same receiver function to receive arguments of multiple types.

--

--