Middle
What is Inversion of Control?
sobes.tech AI
Answer from AI
Inversion of Control (IoC) is a design principle where the control of creating and binding objects is delegated to an external container or framework, rather than being implemented directly in the code.
Instead of the object creating its dependencies itself, they are "injected" from outside. This increases modularity, testability, and flexibility of the code.
In Go, IoC is often implemented through passing dependencies via constructors or functions, rather than through global variables or creation inside functions.
Example of simple dependency injection in Go:
package main
import "fmt"
type Service interface {
Serve()
}
type MyService struct{}
func (s *MyService) Serve() {
fmt.Println("Service is serving")
}
// Consumer depends on Service but does not create it itself
func NewConsumer(s Service) *Consumer {
return &Consumer{service: s}
}
type Consumer struct {
service Service
}
func (c *Consumer) Do() {
c.service.Serve()
}
func main() {
service := &MyService{}
consumer := NewConsumer(service) // dependency injection
consumer.Do()
}
Here, Consumer does not create MyService itself but receives it from outside — this is IoC.