In this tutorial, you will learn about the concept of methods in Golang. Methods and functions are not so different while using regular things you can use functions but when functions move into a concept called classes they are termed as methods. You will understand methods, what makes them different from normal functions in this tutorial.
Go programming language does not support classes in inheritance like other object-oriented programming languages. The Go supports types and methods that allow Golang to perform programs like object-oriented programming languages.
A method is a function with a special receiver argument the receiver appears within its own argument list like (receiver receiver_type
) between func
keyword and method name. The receiver can be a struct or non-struct type.
In methods, the class concept does not exist instead you can use the struct concept. The functions are brought into a struct that defines a method. Let us understand how to define a method in go program.
Syntax to declare a method
func (receiver receiver_type) method_name(arguments) return_type {
return_values
}
Where
Let us understand the method concept with a given program.
The program defines a struct type named emp_details with the following fields Name, Age, Place, Id, salary of string, and integer data types.
// Defining a struct type
type emp_details struct {
Name string
Age int
Place string
Id int
salary int
The defined struct type emp_details
has two methods getUserDetails()
and getUserPlace()
respectively.
func (e1 emp_details) getUserDetails(){ //method 1
fmt.Println("Name of employee is : ",e1.Name )
fmt.Println("Age of employee is : ",e1.Age )
fmt.Println("ID of employee is : ",e1.Id )
}
This is the first method named getUserDetails()
with receiver e1 and receiver type emp_details
. In the receiver declaration, the instance of emp_details is assigned to variable e1. The curly braces enclose certain print statements which return the values for fields defined in struct type emp_details. The below figure illustrates the functioning of the method.
Let us know the next method used which is getUserPlace()
.
func (e1 emp_details) getUserPlace() string { //method 2
return e1.Place
}
As in the same way, the receiver declaration part is composed of (e1 emp_details
) where e1 is the variable to which instances of emp_details are assigned. The method receives a return value data type string.
Note: You are passing the receiver (e1 emp_details) to the getUserPlace() method by value which means inside the method you have a copy of all the emp_details.
package main
import "fmt"
// Defining a struct type
type emp_details struct {
Name string
Age int
Place string
Id int
salary int
}
func (e1 emp_details) getUserDetails(){ //method
fmt.Println("Name of employee is : ",e1.Name )
fmt.Println("Age of employee is : ",e1.Age )
fmt.Println("ID of employee is : ",e1.Id )
}
func (e1 emp_details) getUserPlace() string { //method
return e1.Place
}
func main() {
//Declaring and Initializing variable of struct type
e1 := emp_details{"miya", 20,"Mumbai",0067,20000}
fmt.Println("Given employee details :",e1)
e1. getUserDetails()
fmt.Println("employee place is :",e1.getUserPlace())
}
Output:
Given employee details : {miya 20 Mumbai 55 20000} Name of employee is : miya Age of employee is : 20 ID of employee is : 55 employee place is : Mumbai
type then it is a method of that type. A function attached to a type with a receiver. This means if you attach a function with a type that function is called a receiver function. The receiver function is the method.
Let us understand with an example. The below program will make you understand what a function is and what is method. How do they differ?
Table showing difference of method and function
Method | function |
---|---|
The method has a receiver argument Eg (m method) (receiver receiver_type) |
No receiver argument |
Different methods with the same receiver name can exist. Eg func (m method) add() int func (m method) sub() int |
Different functions with the same name cannot exist Eg func add(x int, y int) int func sub(x, y int) int |
The methods use receivers of either struct or non-struct type. | Functions don’t have receivers so no such concept. |
Note: Compare the examples in the table with the above picture to better understand the concept
package main
import "fmt"
type method struct{
x int
y int
}
func (m method) add() int { //declaring method1
return m.x + m.y
}
func (m method) sub() int { //declaring method 2
return m.x - m.y
}
func add(x int, y int) int { //declaring a function function
return x + y
}
func sub(x, y int) int { //sub function of omit type
return x - y
}
func main() {
m := method{x:3,y:6} //intitializing
fmt.Println("The addition result using method is ", m.add()) //calling method 1
fmt.Println("The addition result using function ",add(10, 5)) //calling function add
fmt.Println("The subtraction result using method is ", m.sub()) //calling method 2
fmt.Println("The subtraction result using function is ",sub(10, 5)) // calling function sub
}
Output:
The addition result using method is 9 The addition result using function 15 The subtraction result using method is -3 The subtraction result using function is 5
Note: The above-discussed method is of struct types.
Go programming language supports methods defined on struct types. The below-given program is defined with a struct of type square using the keyword struct
inside has the attribute side of the integer data type.
Next, a method is defined which operates on squares. In order to define a method use keywords func
followed by parentheses. Inside the parentheses, the method needs to operate is given here it is square. The square is referred to inside the method s. The name of the method is area()
with return type as integer. The area() is responsible for computing the area of the square.
Here the s is passed through the method & accessing the attribute side using the dot operator.
Inside the main function call to this method is defined for that we define a variable s for square with its values initialized.
package main
import ("fmt")
type square struct{ //defining a struct type
side int
}
func (s square ) area() int{ //area of square = side * side
return s.side* s.side
}
func main() {
s := square{side : 3} //Declaring and initializing a struct using a struct literal
fmt.Println("Area of square is : ",s.area(),"cm^2") // call to method area()
}
Output:
Area of square is: 9 cm^2
Note: The method uses a value type receiver
func (s square ) area() int{
return s.side* s.side
}
The key difference from the above program is passing a pointer opposite to the value type receiver.
In the below program the main function defines a square s and a pointer to that square and calls the method s_ptr.perimeter () inside the print function which takes a pointer input and prints output as shown below.
package main
import ("fmt")
type square struct{ //defining a struct type
side int
}
func (s square ) area() int{ //area of square = side * side
return s.side* s.side
}
func (s *square) perimeter() int { //pointer to the struct type square
return 4 * s.side
}
func main() {
s := square{side : 3} //Declaring and initializing a struct using a struct literal
fmt.Println("Area of square is : ",s.area(),"cm^2")
s_ptr := &s //define a pointer
fmt.Println("The perimeter of a square is 4 * sides :", s_ptr.perimeter())
}
Output:
Area of square is : 9 cm^2 The perimeter of a square is 4 * sides : 12