golang

How to use a constructor in Go Lang


In this article, you are going to learn about how to use a constructor in the Go language.

In general, a constructor refers to a special type of function of a class that initializes the object of a class. Basically, it has a similar name to the class name itself and it does not have any return value. Like some other programming languages, the Go language does not have any default constructor but you may declare methods or use some equivalents of a constructor. Let’s see an example of it in the following section:

package main

import "fmt"

type Student struct {
	Name string
	Id   int
}

func (student *Student) Init(name string, id int) {
	student.Name = name
	student.Id = id
}

func studentDetails(name string, id int) *Student {
	student := new(Student)
	student.Name = name
	student.Id = id
	return student
}

func main() {
	std := new(Student)
	std.Init("Gabriel", 1703065)
	fmt.Println(std.Name, std.Id)

	studentDetails := studentDetails("Gabriel", 1703065)
	fmt.Println(studentDetails)
}

/*Output:
  Gabriel 1703065
  &{Gabriel 1703065}
*/

Here, in the above example, we took a Student struct where a student’s name and id will be accepted. After that, we have used the function pointer and also used the Init method and finally, you can see the result in the output. As we have already discussed before the Go language does not support constructors directly but by following this approach you may be able to implement a constructor in your Go language program.


Share on social media

//