Open In App

How to add a method to struct type in Golang?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Structs consist of data, but apart from this, structs also tell about the behavior in the form of methods. Methods attached to structs is very much similar to the definition of normal functions, the only variation is that you need to additionally specify its type.

A normal function returning an integer and taking no parameter would look like.

func function_name() int {
    //code
}

Associating the above-mentioned function with the type type_name() would look like.

type type_name struct { }
func (m type_name) function_name() int {
    //code
}

In the below code, an Area() function is added to a struct Rect. Here, Area() is working explicitly with Rect type with func (re Rect) Area() int

Example:




package main
  
import "fmt"
  
// taking a struct
type Rect struct {
    len, wid int
}
  
func (re Rect) Area() int {
    return re.len * re.wid
}
  
func main() {
    r := Rect{10, 12}
    fmt.Println("Length and Width are:", r)
    fmt.Println("Area of Rectangle: ", r.Area())
}


Output:

Length and Width are: {10, 12}
Area of Rectangle: 120

Go language does not use keywords like this or self, rather, in Go language, when you define a method associated with a type, it is given as a named variable (r Rect) (for eg. in the above case) and then within that method re variable is used.

In the above code, the instance of Rect is passed as a value, to call the method Area(). You can also pass it by reference. There will be no difference in calling the method whether the instance you are using to call it with is a pointer or a value, Go will automatically do the conversion for you.




package main
  
import "fmt"
  
// taking a struct
type Rect struct {
    len, wid int
}
  
func (re Rect) Area_by_value() int {
    return re.len * re.wid
}
  
func (re *Rect) Area_by_reference() int {
    return re.len * re.wid
}
  
// main function
func main() {
    r := Rect{10, 12}
    fmt.Println("Length and Width is:", r)
    fmt.Println("Area of Rectangle is:", r.Area_by_value())
    fmt.Println("Area of Rectangle is:", r.Area_by_reference())
    fmt.Println("Area of Rectangle is:", (&r).Area_by_value())
    fmt.Println("Area of Rectangle is:", (&r).Area_by_reference())
}


Output:

Length and Width is: {10, 12}
Area of Rectangle is: 120
Area of Rectangle is: 120
Area of Rectangle is: 120
Area of Rectangle is: 120

In the above code, we defined two similar methods, one takes the instance(Rect) as a pointer and another take it by value. Both the methods are called via a value r and as an address &r. But since Go perform appropriate conversions, it displays the same results.



Last Updated : 22 Jun, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads