英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论