Methods in Golang

16 Sep, 2021
Go language support methods. Go methods are similar to Go function with one difference, i.e, the method contains a receiver argument in it. With the help of the receiver argument, the method can access the properties of the receiver. Here, the receiver can be of struct type or non-struct type. When you create a method in your code the receiver and receiver type must be present in the same package. And you are not allowed to create a method in which the receiver type is already defined in another package including inbuilt type like int, string, etc. If you try to do so, then the compiler will give an error.
Syntax: 
func(reciver_name Type) method_name(parameter_list)(return_type){
// Code
}
Here, the receiver can be accessed within the method.
In Go language, you are allowed to define a method whose receiver is of a struct type. This receiver is accessible inside the method as shown in the below example:
Example:
Go
// Go program to illustrate the// method with struct type receiverpackage main import "fmt" // Author structuretype author struct {    name      string    branch    string    particles int    salary    int} // Method with a receiver// of author typefunc (a author) show() {     fmt.Println("Author's Name: ", a.name)    fmt.Println("Branch Name: ", a.branch)    fmt.Println("Published articles: ", a.particles)    fmt.Println("Salary: ", a.salary)} // Main functionfunc main() {     // Initializing the values    // of the author structure    res := author{        name:      "Sona",        branch:    "CSE",        particles: 203,        salary:    34000,    }     // Calling the method    res.show()}
Output: 
Author's Name:  Sona
Branch Name:  CSE
Published articles:  203
Salary:  34000
In Go language, you are allowed to create a method with non-struct type receiver as long as the type and the method definitions are present in the same package. If they present in different packages like int, string, etc, then the compiler will give an error because they are defined in different packages.
Example:
Go
// Go program to illustrate the method// with non-struct type receiverpackage main import "fmt" // Type definitiontype data int // Defining a method with// non-struct type receiverfunc (d1 data) multiply(d2 data) data {    return d1 * d2} /*// if you try to run this code,// then compiler will throw an errorfunc(d1 int)multiply(d2 int)int{return d1 * d2}*/ // Main functionfunc main() {    value1 := data(23)    value2 := data(20)    res := value1.multiply(value2)    fmt.Println("Final result: ", res)}
Output: 
Final result:  460
In Go language, you are allowed to create a method with a pointer receiver. With the help of a pointer receiver, if a change is made in the method, it will reflect in the caller which is not possible with the value receiver methods.
Syntax: 
func (p *Type) method_name(...Type) Type {
// Code
}
Example:
Go
// Go program to illustrate pointer receiverpackage main import "fmt" // Author structuretype author struct {    name      string    branch    string    particles int} // Method with a receiver of author typefunc (a *author) show(abranch string) {    (*a).branch = abranch} // Main functionfunc main() {     // Initializing the values    // of the author structure    res := author{        name:   "Sona",        branch: "CSE",    }     fmt.Println("Author's name: ", res.name)    fmt.Println("Branch Name(Before): ", res.branch)     // Creating a pointer    p := &res     // Calling the show method    p.show("ECE")    fmt.Println("Author's name: ", res.name)    fmt.Println("Branch Name(After): ", res.branch)}
Output:
Author's name:  Sona
Branch Name(Before):  CSE
Author's name:  Sona
Branch Name(After):  ECE
As we know that in Go, when a function has a value argument, then it will only accept the values of the parameter, and if you try to pass a pointer to a value function, then it will not accept and vice versa. But a Go method can accept both value and pointer, whether it is defined with pointer or value receiver. As shown in the below example:
Example:
Go
// Go program to illustrate how the// method can accept pointer and value package main import "fmt" // Author structuretype author struct {    name   string    branch string} // Method with a pointer// receiver of author typefunc (a *author) show_1(abranch string) {    (*a).branch = abranch} // Method with a value// receiver of author typefunc (a author) show_2() {     a.name = "Gourav"    fmt.Println("Author's name(Before) : ", a.name)} // Main functionfunc main() {     // Initializing the values    // of the author structure    res := author{        name:   "Sona",        branch: "CSE",    }     fmt.Println("Branch Name(Before): ", res.branch)     // Calling the show_1 method    // (pointer method) with value    res.show_1("ECE")    fmt.Println("Branch Name(After): ", res.branch)     // Calling the show_2 method    // (value method) with a pointer    (&res).show_2()    fmt.Println("Author's name(After): ", res.name)}
Output: 
Branch Name(Before):  CSE
Branch Name(After):  ECE
Author's name(Before) :  Gourav
Author's name(After):  Sona
 
ManasChhabra2
shashwatjain
Go-Functions
Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to concatenate two strings in Golang
time.Sleep() Function in Golang With Examples
strings.Contains Function in Golang with Examples
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
Golang Maps
Time Formatting in Golang
Interfaces in Golang
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?