Create a Go struct constructor by defining a function that returns a pointer to an initialized struct instance.
Define a function that returns a pointer to your struct, initializing its fields within the function body. This pattern, often named New followed by the struct name, ensures the caller receives a ready-to-use instance without exposing internal initialization logic.
type User struct {
ID int
Name string
}
func NewUser(id int, name string) *User {
return &User{
ID: id,
Name: name,
}
}
A constructor function is a standard way to create and set up a new object in Go. Instead of creating an empty object and filling it in manually, you call this function to get a fully prepared object ready to use immediately. Think of it like ordering a pre-assembled computer instead of buying parts and building it yourself.