将Google注入的代码与提供者函数的多个返回值连接起来。

huangapple go评论77阅读模式
英文:

Wire google Inject with multi return from provider function

问题

按照谷歌Wire的示例,我们可以通过以下方式初始化Event结构:

Message.go:

type Message string

func NewMessage() Message {
    //TBD    
}

Event.go:

func NewEvent(g Message) Event {
    return Event{Message: g}
}

type Event struct {
    Message message
}

func (e Event) Start() {
   fmt.Println(msg)
}

然后我们可以通过wire进行初始化:

func main() {
    e := InitializeEvent()
    e.Start()
}

func InitializeEvent() Event {
    wire.Build(NewEvent, NewMessage)
    return Event{}
}

有没有办法处理返回多个值的初始化函数,但我们只需要一个返回值进行注入呢?例如:

func NewMessage() (Message, error) {
    //TBD
}

或者

func NewMessage() (Message, Greeter) {
    //TBD
}
英文:

Follow by example by google wire , we can init Event struct by

Message.go :

type Message string

func NewMessage() Message {
    //TBD    
}

Event.go

func NewEvent(g Message ) Event {
    return Event{Message : g}
}

type Event struct {
    Message message
}

func (e Event) Start() {
   fmt.Println(msg)
}

And we can init by wire :

func main() {
    e := InitializeEvent()
    e.Start()
}
    
func InitializeEvent() Event {
    wire.Build(NewEvent, NewMessage)
    return Event{}
}

Is there any way to work with init function return multi value but we only need one return value to inject, ex:

func NewMessage() (Message,error ){
    //TBD
}

or

func NewMessage() (Message,Greeter) {
    //TBD
}

答案1

得分: 2

声明具有多个返回值的函数,需要将它们放在括号中:

func NewMessage() (Message, error) {
    return Message("TBD"), nil
}

编辑:你正在问的问题(是否可以从init函数返回错误)在Wire教程的下一部分中有答案-https://github.com/google/wire/tree/main/_tutorial#making-changes-with-wire

英文:

To declare a function with multiple return values, you need to put them in parentheses:

func NewMessage() (Message, error) {
    return Message(“TBD”), nil
}

EDIT: The question you're asking (whether you can return an error from the init functions) is answered in the next part of the Wire tutorial - https://github.com/google/wire/tree/main/_tutorial#making-changes-with-wire

huangapple
  • 本文由 发表于 2022年12月1日 15:03:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/74638034.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定