Manually implement dependency injection in Go by defining interfaces for your dependencies and passing concrete implementations into your struct via a constructor function.
type Repository interface {
Get(id string) (*User, error)
}
type UserService struct {
repo Repository
}
func NewUserService(repo Repository) *UserService {
return &UserService{repo: repo}
}
func (s *UserService) GetUser(id string) (*User, error) {
return s.repo.Get(id)
}
// Usage
func main() {
realRepo := &PostgresRepository{}
service := NewUserService(realRepo)
_ = service.GetUser("123")
}