How to Use Constructor Injection in Go

Go requires manual constructor injection by passing dependencies as arguments to a custom constructor function.

Go does not support constructor injection natively; you must manually instantiate dependencies and pass them into your struct's constructor function. Define a constructor function that accepts your dependencies as arguments and returns a pointer to the initialized struct.

type Service struct {
    client *http.Client
}

func NewService(client *http.Client) *Service {
    return &Service{client: client}
}

func main() {
    client := &http.Client{}
    svc := NewService(client)
}