How to Create a Struct Constructor Function in Go

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,
	}
}