大体记载一下go的依赖注入库 dig,它是uber的开源库
大家都知道,java有很多的依赖注入库,而且依赖注入的强大的sprig有更多使用的地方,
好,开征~
go get go.uber.org/dig
直接上一个简单的例子提供大家打开思路
package main
import (
"fmt"
"go.uber.org/dig"
)
type Animal struct {
Name string `json:"name"`
Color string`json:"color"`
}
func main() {
ret := struct {
dig.In
Name string
Color string
}{}
container := dig.New()
container.Provide(NewAnimal)
err := container.Invoke(func(a *Animal) {
ret.Name = a.Name
ret.Color = a.Color
})
if err != nil{
fmt.Println(err.Error())
return
}
fmt.Println(ret.Name)
fmt.Println(ret.Color)
}
func NewAnimal() (a *Animal) {
a=&Animal{
Name: "dog",
Color: "black",
}
return
}
这就是基本的用法,还有什么dig.out我没搞,先打开思路,,然后再深入