What is the Constructor in Golang

Golang does not have built-in support for Constructor; however, you can use the “factory functions (also known as constructor functions)” to initialize and return a new instance of a custom type, like a struct. A factory function is just a regular function that creates an instance of a type, initializes it, and returns it.

Example

package main

import "fmt"

// Define a custom struct
type Student struct {
  FirstName string
  LastName string
  Age int
}

// NewStudent is a factory function (constructor) for the Student struct
func NewStudent(firstName, lastName string, age int) *Student {
  return &Student{
    FirstName: firstName,
    LastName: lastName,
    Age: age,
  }
}

func main() {
  // Create a new instance of the Student struct using the factory function
  Student := NewStudent("Krunal", "Lathiya", 22)

  fmt.Println("Student:", Student)
}

Output

Student: &{Krunal Lathiya 22}

In the above code, we defined a custom struct called Student with FirstName, LastName, and Age fields.

In the next step, we defined a factory function NewStudent that takes the required information as arguments and initializes a new Student instance with the provided values. Finally, the function returns a pointer to the new instance.

In the main() function, we use the NewStudent factory function to create and print a new Student instance.

It’s worth noting that the name of the factory function often starts with “New” followed by the type name (e.g., NewStudent). However, this naming convention is not enforced by the language, and you can choose a different name if it makes more sense for your use case.

Leave a Comment