← 返回 Golang 列表

Go 模块管理与依赖注入

go.mod 版本管理与依赖注入模式,构建可测试的 Go 应用。

Go Modules 基础

go mod init example.com/myapp
go mod tidy
go build ./...

依赖注入(手动 DI)

Go 社区倾向手动 DI,通过构造函数注入依赖,避免反射框架。

type Service struct {
  repo Repository
}

func NewService(r Repository) *Service {
  return &Service{repo: r}
}
提示: 接口注入+构造函数,测试时可轻松替换 Mock。