Dependency Injection in Go
Start with Dependency Injection in Go
Learn dependency injection in go through an executable example, then connect the small demonstration to production code.
What you’ll learn
- Explain the main purpose of dependency injection in go.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Dependency injection means supplying what a component depends on instead of constructing it deep inside that component. Go typically uses constructors, fields and small interfaces rather than a special framework.
The notifier is passed to the service, allowing an in-memory replacement during tests.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
type Sender interface{ Send(string) error }
type Recorder struct{ Messages []string }
func (r *Recorder) Send(s string) error { r.Messages = append(r.Messages, s); return nil }
type WelcomeService struct{ Sender Sender }
func (w WelcomeService) Welcome(name string) error { return w.Sender.Send("Welcome, " + name) }
func main() {
recorder := &Recorder{}
service := WelcomeService{Sender: recorder}
_ = service.Welcome("Mina")
fmt.Println(recorder.Messages)
}
Output
[Welcome, Mina]Trace what the program does
The injected Recorder records the outgoing message rather than sending email. The service knows only that a Sender can Send a string.
Avoid common mistakes
- Inject only dependencies that genuinely vary or complicate tests.
- A nil interface dependency can panic when a method is called; validate required wiring.
Try it yourself
Implement a ConsoleSender that prints messages and swap it into WelcomeService.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Dependency Injection in Go in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.