AppDividend
Latest Code Tutorials

Golang Receiver Function Tutorial | Go Function Receivers Example

0

Golang Receiver Function Tutorial With Example is today’s topic. Go is very similar to C due to the presence of pointers, static typing, and many other things. But Go is the modern language and so it has many new features baked in it, and Function Receiver is one of it. Go is not Object-Oriented Programming Language.

Golang Receiver Function Tutorial

Function Receiver sets a method on variables that we create. This seems weird at first, but when you get the example, it will be clear as crystal.

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, and that method is Receiver function.

With the receiver functions, you don’t have to mess around with classes or deal with inheritance. One advantage of using 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 the how to install Go tutorial.

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 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.

Now, the last step is to create 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()
}

In this code, we have created a variable from the custom type declaration which is app. 

It consists of a slice which 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 following.

Golang Receiver Function Tutorial | Go Function Receivers Example

Finally, Golang Receiver Function Tutorial | Go Function Receivers Example is over.

Recommended Posts

Go Interface Tutorial With Example

Go Arrays Tutorial With Example

Go Structs Tutorial With Example

Go Functions Tutorial With Example

Go Slices Tutorial With Example

Leave A Reply

Your email address will not be published.

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