Difference between functions and methods in Golang

Penthaa
2 min readMar 18, 2021

--

The words function and method are used almost interchangeably, but there are subtle differences in their implementation and usage when used in Golang. Let’s see what the difference is and how its used.

Function

Functions accept a set of input parameters, perform some operations on the input and produce an output with a specific return type. Functions are independent that is they are not attached to any user defined type.

Syntax:

There cannot exist two different functions with the same name in the same package.

Run above code in The Go Playground

The above code throws an error : Area redeclared in this block

Method

A method is effectively a function attached to a user defined type like a struct. This user defined type is called a receiver.

Syntax:

There can exist different methods with the same name with a different receiver.

Run above code in The Go Playground

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Penthaa
Penthaa

Written by Penthaa

Infosec | Gopher | CSE Grad from IIIT-Bh | Find me on — GitHub - github.com/penthaapatel | Website — penthaapatel.github.io

No responses yet

Write a response