Functions vs Methods in Golang

Go ProgrammingServer Side ProgrammingProgramming

In this article, we will learn what similarities and differences are there between functions and methods in Golang. We will start with each of them separately, and then we will see an example where both of them will be used.

Let's start with functions and see what they are and how to use them in Golang.

Functions in Golang

Functions in Golang are a block of code that take a few parameters as input and produce some output. If we pass in the same input to a function, it will produce the same output as always.

Example 1

In this example, we are creating a function and then calling it from the main function.

package main

import (
   "fmt"
)

func height(x, y int) int {
   return 2 * (x + y)
}

func main() {
   x, y := 10, 20

   res := height(x, y)

   fmt.Println("The result is:", res)
}

In the above code, we have declared a function named height() which has two defined parameters, x and y, respectively.

Output

If we run the above code with the command go run main.go then we will get the following output.

The result is: 60

Methods in Golang

A method in Golang is like a function that needs a receiver to get invoked. In simple words, a method is a function that is defined on struct types.

Example 2

Let's consider an example where we will create a method and then use it.

package main

import (
   "fmt"
)

type shape struct {
   x int
   y int
}

func (s shape) height() int {
   return 2 * (s.x + s.y)
}

func main() {

   res1 := shape{x: 10, y: 20}

   fmt.Println("The result1 is:", res1.height())
}

Output

If we run the above code with the command go run main.go then we will get the following output.

The result1 is: 60

Differences between Functions and Methods in Golang

The notable differences can be interpreted by the examples shown above for both the functions and methods. The main difference comes down to the receiver which is there in a method and not in a function.

The other difference is in how we execute them, like in the case when we call them.

Consider the code snippet shown below.

res1 := shape{x: 10, y: 20}// for methods
res := height(x, y) // for functions
raja
Updated on 01-Nov-2021 07:08:11

Advertisements