Monday 6 May 2019

Go Language: Adding Methods to a struct


In my previous post, I explained how to create a struct and add fields to it. In this post, I am going to explain how can you add methods to a structure.

type MyType struct { }

func (m MyType) myFunc() int {
   //code
}

Above snippet add new function ‘myFunc’ to the structure MyType.

HelloWorld.go
package main

import "fmt"

func main() {
 emp1 := new(Employee)
 emp1.name = "Krishna"
 emp1.id = 123

 emp1.printEmployeeInfo()

}

type Employee struct {
 name string
 id   int
}

func (emp Employee) printEmployeeInfo() {
 fmt.Println("name : ", emp.name, ", id : ", emp.id)
}

Output
name :  Krishna , id :  123

One advantage of adding methods to a structure like this is, There is clear separation between data and the methods.

Let’s see another example, where I am going to add a method ‘capitalizeName’, which capitalizes the employee name.

func (emp Employee) capitalizeName() {
         emp.name = strings.ToUpper(emp.name)
}


App.go
package main

import "fmt"
import "strings"

func main() {
 emp1 := new(Employee)
 emp1.name = "Krishna"
 emp1.id = 123

 emp1.printEmployeeInfo()
 emp1.capitalizeName()
 fmt.Println("After calling capitalizeName method")
 emp1.printEmployeeInfo()

}

type Employee struct {
 name string
 id   int
}

func (emp Employee) printEmployeeInfo() {
 fmt.Println("name : ", emp.name, ", id : ", emp.id)
}

func (emp Employee) capitalizeName() {
 emp.name = strings.ToUpper(emp.name)
}

Output
name :  Krishna , id :  123
After calling capitalizeName method
name :  Krishna , id :  123

As you see the output, name is not getting capitalized after calling ‘capitalizeName()’ method. The reason is that you are not using a pointer receiver. Change ‘capitalizeName’ method signature like below to make the things right.

func (emp *Employee) capitalizeName() {
         emp.name = strings.ToUpper(emp.name)
}

App.go
package main

import "fmt"
import "strings"

func main() {
 emp1 := new(Employee)
 emp1.name = "Krishna"
 emp1.id = 123

 emp1.printEmployeeInfo()
 emp1.capitalizeName()
 fmt.Println("After calling capitalizeName method")
 emp1.printEmployeeInfo()

}

type Employee struct {
 name string
 id   int
}

func (emp Employee) printEmployeeInfo() {
 fmt.Println("name : ", emp.name, ", id : ", emp.id)
}

func (emp *Employee) capitalizeName() {
 emp.name = strings.ToUpper(emp.name)
}

Output
name :  Krishna , id :  123
After calling capitalizeName method
name :  KRISHNA , id :  123





Previous                                                 Next                                                 Home

No comments:

Post a Comment