Sobes.tech
Junior — Middle

How is the dependency inversion principle implemented in Go?

sobes.tech AI

Answer from AI

In Go, the principle of dependency inversion is implemented through the use of interfaces and manual dependency injection.

The main idea is to define an interface that describes behavior, and then pass objects implementing this interface to functions or structures. This way, high-level modules depend on abstractions, not on concrete implementations.

Example:

// Interface
 type Notifier interface {
     Notify(message string) error
 }

// Concrete implementation
 type EmailNotifier struct {}

 func (e EmailNotifier) Notify(message string) error {
     // send email
     return nil
 }

// Function accepting an interface
 func SendAlert(n Notifier, msg string) {
     n.Notify(msg)
 }

func main() {
     email := EmailNotifier{}
     SendAlert(email, "Important message")
}

Thus, it is easy to change implementations without modifying the code that uses them.