Golang Receiver Function

A receiver function in Go is “defined within a type.” The receiver function is associated with the type and can only be called on instances of that type.

To define a receiver function, specify the receiver type in parentheses before the function name. The receiver is usually a pointer to the type, allowing you to modify the original value, but it can also be a value type.

Syntax

func (receiver_type receiver_name) function_name(parameters) (return_values) {
   // function body
}

Parameters

The receiver_type is the type on which the method is defined.

The receiver_name is the name of the receiver parameter.

The function_name is the name of the method.

The parameters are the parameters of the method. The return_values are the return values of the method.

Example

package main

import (
  "fmt"
)

 // Define a custom type called "MyInt" based on "int"
 type MyInt int

 // Define a receiver function "Add" for the "MyInt" type
 func (mi *MyInt) Add(n int) {
   *mi = *mi + MyInt(n)
 }

 func main() {
  // Create a variable of type MyInt
  var num MyInt = 21
  fmt.Println("Initial value of num:", num)

  // Call the Add receiver function on the num variable
  num.Add(10)
  fmt.Println("Value of num after adding 10:", num)
}

Output

Initial value of num: 21

Value of num after adding 10: 31

Benefits of receiver function in Go

Here are some of the benefits of using receiver functions in Go:

  1. Encapsulation: Receiver functions can help you encapsulate the implementation of methods within the type definition. This makes your code more modular and easier to understand.
  2. Type safety: Receiver functions ensure that methods can only be called on instances of the correct type. This helps to prevent errors and improve the safety of your code.
  3. Performance: Receiver functions can improve the performance of your code by avoiding the need to pass copies of data to methods.

That’s it.

Leave a Comment

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