GO Methods vs Functions [In-Depth Explanation]


Written by - Deepak Prasad

This tutorial explores the distinctions between Go's functions and methods, covering their declaration, usage, practical examples, and best practices for effective Go programming.

 

In Go, functions and methods are fundamental constructs used to define behavior and manipulate data. While they share some similarities, they have distinct characteristics and use cases within the language.

Functions in Go are independent blocks of code that perform specific tasks. They are defined using the func keyword, can take input parameters, and may return values. Functions are standalone, meaning they aren't associated with any specific type or struct, and can be invoked from anywhere in your code. They are suitable for tasks that aren't inherently tied to a specific data structure or object.

Methods in Go, on the other hand, are functions attached to a specific type or struct. They are also defined using the func keyword but include a receiver argument that binds them to the type. Methods can access and modify the internal fields of the type to which they are attached, allowing for more object-oriented programming within Go. This association with specific types makes methods particularly useful for implementing behavior that is inherently related to the data structure they are bound to.

 

1. Are Go Functions and Methods same?

No, I am afraid not. This is one general misconception among many techies.

In Go, a function is a standalone piece of code that can be called by other parts of your program. A method is a function that is associated with a specific type or struct.

The main difference between a function and a method is that a method is associated with a specific type or struct, whereas a function is standalone code that can be called from anywhere in your program. When a method is called, it has access to the fields and properties of the struct it is associated with, whereas a function does not.

Secondly there is some difference in the syntax of method and function, in method the first parameter is always the receiver which is the instance of the struct the method is associated with.

In Go, you can define methods on structs, interfaces, and even on built-in types like int.

Let's look at some examples

 

2. Comparison of Functions and Methods

Functions and methods in Go serve distinct purposes and have different implications for code structure and organization. Here's a comparison highlighting their main differences:

 

2.1 Syntax Differences

Functions:

  • Declared using the func keyword.
  • Syntax: func FunctionName(params Type) returnType {}.
func Add(a, b int) int {
    return a + b
}

Methods:

  • Also use the func keyword, but include a receiver argument.
  • Syntax: func (receiverName ReceiverType) MethodName(params) returnType {}.
type Circle struct {
    radius float64
}

func (c Circle) Area() float64 {
    return math.Pi * c.radius * c.radius
}

 

2.2 Association and Access to Data

Functions:

  • Standalone, not associated with any specific type.
  • Don't have access to the internal data of a type unless explicitly passed as an argument.

Methods:

  • Associated with a specific type or struct (ReceiverType in the syntax).
  • Can access and modify the internal fields of the type they are associated with.

 

2.3 Appropriate Usage

Functions are more suitable for:

  • Generic operations that are not tied to a specific type.
  • Utility tasks that can be applied across different types.
  • Independent logic that doesn't require access to the internal state of an object.

Methods are better used for:

  • Operations that are intrinsically tied to the data of a specific type.
  • Encapsulating behavior within a type, enhancing readability and maintainability.
  • Object-oriented programming concepts in Go, such as defining behavior specific to a struct.

 

2.4 Practical Example

Consider a scenario with a Circle struct and the task of calculating its area:

Using a Function:

type Circle struct {
    radius float64
}

func CalculateArea(c Circle) float64 {
    return math.Pi * c.radius * c.radius
}

func main() {
    circle := Circle{radius: 5}
    area := CalculateArea(circle)
    fmt.Println(area)
}

In the function example, CalculateArea is a standalone function that takes a Circle type as an argument and returns its area. This function can be called with any Circle instance, but it's not tied to the Circle type.

Using a Method:

type Circle struct {
    radius float64
}

func (c Circle) Area() float64 {
    return math.Pi * c.radius *
    radius * c.radius
}

func main() {
    circle := Circle{radius: 5}
    area := circle.Area()
    fmt.Println(area)
}

In the method example, Area is a method tied to the Circle type, indicated by the (c Circle) receiver in its declaration. It can access the radius property directly and is called on an instance of Circle using the dot notation (circle.Area()).

The choice between using a function or a method in Go depends on the context:

  • Use a function for operations that don't need to access or modify the internal state of a type.
  • Use a method for operations that are closely related to a type and might need to access or modify its internal state.

 

3. Practical Code Example to understand the difference

To illustrate the use of functions and methods in Go and how similar tasks can be achieved using both approaches, let's consider a practical example involving a simple task: Calculating the area of a rectangle.

 

3.1 Using a Function

First, we define a Rectangle struct and a standalone function to calculate the area.

package main

import (
    "fmt"
)

type Rectangle struct {
    length, width float64
}

func CalculateArea(rect Rectangle) float64 {
    return rect.length * rect.width
}

func main() {
    rect := Rectangle{length: 10, width: 5}
    area := CalculateArea(rect)
    fmt.Println("Area using function:", area)
}

In this approach, CalculateArea is a function that takes a Rectangle object as a parameter and returns the calculated area. It is a standalone function and not associated with the Rectangle type directly.

 

3.2 Using a Method

Now, let's achieve the same using a method associated with the Rectangle struct.

package main

import (
    "fmt"
)

type Rectangle struct {
    length, width float64
}

func (r Rectangle) Area() float64 {
    return r.length * r.width
}

func main() {
    rect := Rectangle{length: 10, width: 5}
    area := rect.Area()
    fmt.Println("Area using method:", area)
}

Here, Area is a method defined with a receiver of type Rectangle. It can be called on any instance of Rectangle, as demonstrated in the main function. This method is more tightly coupled to the Rectangle type and can access its properties directly.

Both the function and the method achieve the same result, but their association with the data they operate on differs. The function CalculateArea is independent and needs a

Rectangle object passed to it, whereas the method Area is associated with the Rectangle type and operates on an instance of Rectangle. The method approach encapsulates the behavior with the data it operates on, making it part of the Rectangle's definition.

 

4. Summary

In Go, you can use either functions or methods to accomplish a task, and it depends on the situation and personal preference which one to use. Here is a summary of comparison:

  • A function is a standalone piece of code that can be called by other parts of your program.
  • A method is a function that is associated with a specific type or struct.
  • The main difference between a function and a method is that a method is associated with a specific type or struct, whereas a function is standalone code that can be called from anywhere in your program.
  • When a method is called, it has access to the fields and properties of the struct it is associated with, whereas a function does not.
  • The syntax of the method is slightly different than the function, in method the first parameter is always the receiver which is the instance of the struct the method is associated with.
  • In Go, you can define methods on structs, interfaces, and even on built-in types like int, float64, string, etc.

You can also refer Whats the difference of functions and methods in Go? for more information.

 

Deepak Prasad

He is the founder of GoLinuxCloud and brings over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels in various domains, from development to DevOps, Networking, and Security, ensuring robust and efficient solutions for diverse projects. You can reach out to him on his LinkedIn profile or join on Facebook page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment