【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{}
}	
```[]()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM