0
0
GoConceptBeginner · 3 min read

What is Receiver Function in Go: Simple Explanation and Example

In Go, a receiver function is a function that is attached to a specific type, allowing you to call it like a method on that type. It uses a special receiver argument before the function name to access or modify the data of that type.
⚙️

How It Works

Think of a receiver function as a way to give special powers to a type, like a struct. Instead of just having plain data, the type can have actions it can perform, similar to how objects work in other languages.

When you define a receiver function, you write the function with a receiver argument inside parentheses before the function name. This receiver acts like the owner of the function, so inside the function you can use it to access or change the type's data.

For example, if you have a Car type, you can add a receiver function that makes the car start or stop. This helps organize code by grouping related data and behavior together.

💻

Example

This example shows a Person type with a receiver function that greets using the person's name.

go
package main

import "fmt"

type Person struct {
    Name string
}

// greet is a receiver function for Person
func (p Person) greet() {
    fmt.Printf("Hello, my name is %s.\n", p.Name)
}

func main() {
    person := Person{Name: "Alice"}
    person.greet() // calling the receiver function
}
Output
Hello, my name is Alice.
🎯

When to Use

Use receiver functions when you want to add behavior to your custom types in Go. This is useful for organizing code and making it easier to work with data structures.

Common real-world uses include:

  • Adding methods to structs to perform actions or calculations
  • Implementing interfaces by defining required receiver functions
  • Encapsulating logic related to a type, like formatting output or updating fields

Key Points

  • A receiver function is like a method attached to a type.
  • It uses a receiver argument to access the type's data.
  • Receivers can be value or pointer types, affecting whether the function can modify the original data.
  • Receiver functions help organize code and implement interfaces.

Key Takeaways

A receiver function lets you add methods to your Go types for better organization.
Define a receiver in parentheses before the function name to access the type's data.
Use pointer receivers to modify the original data inside the function.
Receiver functions are essential for implementing interfaces in Go.