Dependency Injection (DI) is a design pattern where dependencies are passed into a function or struct rather than created internally, enabling loose coupling and easier testing. In Go, you implement DI by defining interfaces for dependencies and passing concrete implementations via constructor functions or struct fields.
type Service interface {
Process() error
}
type Worker struct {
svc Service
}
func NewWorker(svc Service) *Worker {
return &Worker{svc: svc}
}
This approach lets you swap real implementations for mocks during testing without changing the Worker code.