In this article, we will discuss how to create a constructor in Go using native functions.
Constructor Like Functions
Let us define a simple struct as shown in the code below:
Name string
Age int
Salary float64
}
From the struct, we can create a function like constructor as shown in the example:
u := new(User)
u.Name = name
u.Age = age
u.Salary = salary
return u
}
The above will create a constructor-like function from the User type. If we check the type, we should get:
*main.User
As you see the way to create constructors in Go is to create functions that return an oobject pointer.
An example function is as show:
u.Name = name
u.Age = age
u.Salary = salary
}
We can use the function as:
user.Init("Jonathan Archer", 45, 140000.33)
fmt.Printf("%s: %d: %f\n", user.Name, user.Age, user.Salary)
Conclusion
In this article, we explored how to introduce OOP in Go using structures and functions that return a pointer.