In this article, we shall discuss the major difference between the function and method in Golang programming language.
What is Function in Go
Function in Go is a statement in a program that is used to execute a
specific task. It can be of different kinds closure, Anonymus, etc. Its
created using the keyword func(){} or func funcName()returnType{}.
You can grasp more about functions in our previous article
Functions
In the below code, we are using os and fmt packages to format output
of our function FullName(){} using fmt and reading user input on the
command line arguments using os package.
package main
import (
"fmt"
"os"
)
func FullName(first, last string) string {
return fmt.Sprintf("%s %s", first, last)
}
func main() {
first := os.Args[1]
last := os.Args[2]
fmt.Printf("FirstName is %s, lastName is %s. Your Fullname is %s", first, last, FullName(first, last))
}
OutPut:
$ go run main.go John Doe
FirstName is John, lastName is Doe. Your Fullname is John Doe
What is method in Go
Golang support
methods, It’s a function with special receiver arguments in it. This
method can access the defined properties of the receiver. The receiver
appears in its own argument list between the func keyword of function
and the method name i.e func (t *T) methodName(){}. This receiver can
be of either struct or non-struct type.
Syntax of a Method in Go
// Method using struct
func(receiver name Type)methodName(params)returnType{}
// method with a pointer
func(receiver name *Type)methodName(...paramsType)returnType{}
Example of a method in Go
In the below program, we have defined a struct of a triangle with a base
and height of float64, we used this struct in our method as receiver
func (triangle Triangle) Area() float64 {} and we called our method in
the main function to execute area.
package main
import (
"fmt"
)
// struct
type Triangle struct {
base, height float64
}
// method to calculate area of a triangle
func (triangle Triangle) Area() float64 {
return 0.5 * (triangle.base * triangle.height)
}
func CheckError(err error) {
if err != nil {
fmt.Printf("Error: %v", err)
}
}
func main() {
fmt.Println("Enter the Base of the triangle")
var base float64
_, err:= fmt.Scanf("%f", &base)
CheckError(err)
fmt.Println("Enter the Height of triangle")
var height float64
_, err2:= fmt.Scanf("%f", &height)
CheckError(err2)
area := Triangle{
base: base,
height: height,
}
fmt.Printf("The Area of the triangle of base %v and height %v values is %v. ", base, height, area.Area())
}
Output:
$ go run main.go
Enter the Base of the triangle
24
Enter the Height of the triangle
13
The area of the triangle of base 24 and height 13 values is 156.
Difference and comparison - function vs method in Golang
Example to be used:
package main
import (
"fmt"
)
// struct
type Triangle struct {
base, height float64
}
// method to calaculate area of a triangle
func (triangle Triangle) Area() float64 {
val := 0.5
return val * (triangle.base * triangle.height)
}
// Variable
func Newtriangle(base, height float64) *Triangle {
return &Triangle{
base: base,
height: height,
}
}
// function based on the struct
func AreaOfTriangle(t *Triangle) float64 {
val := 0.5
return val * (t.base * t.height)
}
func CheckError(err error) {
if err != nil {
fmt.Printf("Error: %v", err)
}
}
func main() {
fmt.Println("Enter the Base of triangle")
var base float64
_, err := fmt.Scanf("%f", &base)
CheckError(err)
fmt.Println("Enter the Height of triangle")
var height float64
_, err2 := fmt.Scanf("%f", &height)
CheckError(err2)
// variable assigning
results := Newtriangle(base, height)
fmt.Println("From Function", AreaOfTriangle(results))
fmt.Printf("The Area of the triangle of base %v and height %v values is %v. ", base, height, results.Area())
}
Output
$go run main.go
Enter the Base of triangle
3
Enter the Height of triangle
4
From Function 6
The Area of the triangle of base 3 and height 4 values is 6.
1. Declaration syntax
Function declaration syntax in Golang
isfunc func_name(param paramType) return_paramType{} where we define
the function name and specified the arguments type as well as return
datatype.
Example:-
func AreaOfTriangle(t *Triangle) float64 {
val := 0.5
return val * (t.base * t.height)
}
Explanation:-
In the above code function declarations, we declared
funcArea(t *Triangle) float64 {}, function arguments are (t
*Triangle) from the struct and return type is float64.
Methods declaration syntax in Golang is
func (receiver *receiver_type) func_Name() return_type{}, where we
have to declare the receiver.
Example:-
func (triangle Triangle) Area() float64 {
val := 0.5
return val * (triangle.base * triangle.height)
}
Explanation:- In the above code method declarations, we declared
Area() method on the (triangle *Triangle) type which is the receiver.
2. Program Execution
Functions are executed independently with the arguments specified passed to them.
Example::-
results := Newtriangle(base, height)
// execution to call methods
fmt.Println("From Function", AreaOfTriangle(results))
Explanation:- In the above code, we define a variable to hold
results new variables of a function, which can be passed into a method
for execution
Methods are executed on call to their type receiver. E.g to execute the
above function you have to call the method like results.Area()
Example:-
results := Newtriangle(base, height)
// Execution
result := results.Area()
3. Readability
It refers to the semantics of code or easy-to-read code. From our
example above; we will be focusing on the AreaOfTriangle() and
Area() both are function.
Example:-
results := Newtriangle(base, height)
Function semantics in Go
// function
AreaOfTriangle(results)
Methods semantics in Go
//method
results.Area()
**Explanation:-**In the code above results.Area() you can read it
much better by asking what is the area of the triangle as compared to
AreaOfTriangle(results).
Summary
In this article, We have discussed a lot of the differences between functions and Methods in Go. Golang does not support Object-oriented programming however with the use of methods we can mimic inheritance and other mechanisms used in OOP. Despite those differences, the key difference is in the readability or semantics, Code should always be easy to read and understand. In case a team of developers might prefer using functions to methods. What they agree on becomes the better option for abstraction.
If a function is used to modify a lot of values of a particular data
type, kindly create a method of that type. This is in conjunction with
the Stateless code which should always return the same output as the
same input.
References
Function in Go Tour
Functions
Go Methods
Related Keywords: golang receiver vs function argument, golang receiver vs function argument, golang when to use methods, method and function in golang, golang instance function, golang method pointer vs value receiver, method vs function


