This content originally appeared on CodeSource.io and was authored by Md Niaz Rahman Khan
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.
This content originally appeared on CodeSource.io and was authored by Md Niaz Rahman Khan
Md Niaz Rahman Khan | Sciencx (2022-01-19T16:59:46+00:00) How to use a constructor in Go Lang. Retrieved from https://www.scien.cx/2022/01/19/how-to-use-a-constructor-in-go-lang/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.