Monday, 6 May 2019

Go language: constructor functions


Unlike other languages Java, Go do not have any constructor functions to initialize an object. But you can write custom functions to initialize the object.

Example
func getEmployee(name string, id int, hobbies []string) Employee{
         emp := Employee{}

         emp.name = name
         emp.id = id
         emp.hobbies = hobbies

         return emp
}

HelloWorld.go
package main

import "fmt"

func main() {
 emp1 := getEmployee("Krishna", 1, []string{"Cricket", "Football"})

 fmt.Println("name : ", emp1.name)
 fmt.Println("id : ", emp1.id)
 fmt.Println("hobbies : ", emp1.hobbies)
}

type Employee struct{
 name string
 id int

 hobbies []string
} 

func getEmployee(name string, id int, hobbies []string) Employee{
 emp := Employee{}

 emp.name = name
 emp.id = id
 emp.hobbies = hobbies

 return emp
}

Output
name :  Krishna
id :  1
hobbies :  [Cricket Football]

You can enhance the constructor function by adding some validation checks.

func getEmployee(name string, id int, hobbies []string) (*Employee, error) {
         if name == "" {
                  return nil, fmt.Errorf("Name can't be nil")
         }

         if id <= 0 {
                  return nil, fmt.Errorf("id can't be zero")
         }

         emp := Employee{}

         emp.name = name
         emp.id = id
         emp.hobbies = hobbies

         return &emp, nil
}


HelloWorld.go
package main

import "fmt"

func main() {
 emp1, err1 := getEmployee("Krishna", 1, []string{"Cricket", "Football"})

 if err1 != nil {
  fmt.Println("Error Occurred while creating employee")
  fmt.Println(err1)
 } else {
  emp1.printEmployeeInfo()
 }

 emp2, err2 := getEmployee("Krishna", -10, []string{"Cricket", "Football"})

 if err2 != nil {
  fmt.Println("Error Occurred while creating employee")
  fmt.Println(err2)
 } else {
  emp2.printEmployeeInfo()
 }

}

type Employee struct {
 name string
 id   int

 hobbies []string
}

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

func getEmployee(name string, id int, hobbies []string) (*Employee, error) {
 if name == "" {
  return nil, fmt.Errorf("Name can't be nil")
 }

 if id <= 0 {
  return nil, fmt.Errorf("id can't be zero")
 }

 emp := Employee{}

 emp.name = name
 emp.id = id
 emp.hobbies = hobbies

 return &emp, nil
}

Output
name :  Krishna , id :  1 , hobbies :  [Cricket Football]
Error Occurred while creating employee
id can't be zero


Previous                                                 Next                                                 Home

No comments:

Post a Comment