1. 程式人生 > 實用技巧 >【go】wire的具體各類用法

【go】wire的具體各類用法

本文僅記錄wire的具體使用方法, 而wire這個工具的作用, 功能和優缺點不再贅述

wire的github地址: https://github.com/google/wire

demo中struct依賴關係

場景一 成員變數是結構體型別

用法一: 直接通過各struct的new函式拼裝

自定義了所有struct的new函式, 通過wire.Build()組裝

func InitService1() *Service {
    wire.Build(NewService1, NewRemoteCallA, NewRemoteCallB)
    return &Service{}
}

用法二: 使用ProviderSet(可包含大於等於1個new函式)

將New函式放到ProviderSet裡, 再傳到wire.Build函式內

var RemoteCallSet = wire.NewSet(NewRemoteCallA, NewRemoteCallB)
func InitService2() *Service {
    wire.Build(NewService1, RemoteCallSet)
    return &Service{}
}

ProviderSet裡可以是其他ProviderSet 千層餅一樣巢狀下去

用法三: 最上層struct不需要提供new函式, 以wire.Struct代替

使用wire.Struct() 代替最終要生產的struct的New函式

第二個引數 "*" 表示所有欄位都進行初始化

wire.Value() 作用是將值轉化為一個ProviderSet, 以滿足wire.Build()入參型別

func InitService3() *Service {
    wire.Build(wire.Struct(new(Service), "*"), NewRemoteCallA, NewRemoteCallB, wire.Value("a"))
    return &Service{}
}

用法四: wire.Struct 指定具體欄位

wire.Struct() 不使用 "*" 而是指定具體欄位名

func InitService4() *Service {
    wire.Build(wire.Struct(new(Service), "remoteCallA"), NewRemoteCallA)
    return &Service{}
}

用法五:部分欄位由入參傳入

部分欄位通過入參傳入, 而不是通過wire.Build中指定

func InitService5(rb *RemoteCallB, c string) *Service {
    wire.Build(wire.Struct(new(Service), "*"), NewRemoteCallA)
    return &Service{}
}

需要注意的是結構體裡不能有相同型別的兩個及以上的欄位, 如:

type Service struct {
  a string
  b string
  // ... 其他欄位
}

是不允許的, 解決方法就是使用類型別名解決衝突, 會報錯

provider struct has multiple fields of type string

場景二: 成員變數為interface型別

用法一: 使用返回interface的new函式

func InitService7() *Service2 {
    wire.Build(wire.Struct(new(Service2), "*"), NewRemoteCallInterface, wire.Value("a"))
    return &Service2{}
}

用法二: 使用ProviderSet, 將具體struct的New函式繫結到interface上

var RemoteCallASet = wire.NewSet(NewRemoteCallA, wire.Bind(new(RemoteCall), new(*RemoteCallA)))
func InitService8() *Service2 {
    wire.Build(wire.Struct(new(Service2), "*"), RemoteCallASet, wire.Value("a"))
    return &Service2{}
}	
```[]()