Golang Receiver Function: Step by Step Guide

Go is very similar to C due to the presence of pointers, static typing, and many other things. But Go is the modern language, so it has many new features, and Function Receiver is one of them. Go is not an Object-Oriented Programming Language.

Golang receiver function

Golang Function Receiver sets a method on variables that we create. With Golang receiver functions, you don’t have to mess around with classes or deal with inheritance.

This seems weird initially, but it will be clear as crystal when you get the example.

Let’s create a custom type in Golang and then assign that type to a variable. Now, you can set a method on that variable: the Receiver function.

One advantage of using the receiver function is when we couple it with interfaces.

Let’s understand with the following example.

If you do not know how to install Go on local, then please go through how to install Golang.

Create a file called app.go and add the following code inside it.

/* app.go */

package main

import "fmt"

type app []string

func (a app) print() {
   for i, app := range a {
	fmt.Println(i, app)
   }
}

In the above code, we have created a custom type called app. 

Then we have defined one receiver’s function for this app type.

Now, let’s see the syntax of the function receiver.

func(t type) functionName() {}

In the above code, the type is our custom-defined type, and in our case, it is app.

So, when we create a variable from that type, it has access to this print() method, which is, in our case, a receiver function.

The last step is creating a variable from the custom-defined type inside the hello.go file.

So write the following code inside the hello.go file.

/* hello.go */

package main

func main() {
   apps := app{"Facebook", "Instagram", "WhatsApp"}
   apps.print()
}

We have created a variable from the custom type declaration app in this code

It consists of a slice that has three items.

Then we have called a receiver function called print() which we have defined inside the app.go file.

So, when the print() function is called, it will execute the body of the print() function, which will iterate the slice and display the item one by one through for loop.

You can run the files using the following command.

go run hello.go app.go

The output is the following.

Golang Receiver Function Tutorial | Go Function Receivers Example

That’s it for this tutorial.

Recommended Posts

Golang Interface

Golang Array

Golang Struct

Golang Function

Golang Slice

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.