英文:
Golang - pass struct as argument to function
问题
我必须解析一些嵌套的JSON,它转换成了一个Go类型,就像这样:
type Config struct {
Mail struct {
From string
To string
Password string
}
Summary struct {
Send bool
Interval int
}
}
现在我想为每个键(Mail、Summary)调用一个函数,我尝试了以下方式:
utils.StartNewMailer(config.Mail)
问题是,我该如何构造被调用的函数?我试图复制Mail
结构体(并将其命名为mailConfig
),因为我不能将任意结构体作为参数传递。
func StartNewMailer(conf mailConfig) { //...
但这也不起作用,我得到了以下编译器错误信息:
cannot use config.Mail (type struct { From string; To string; Password string }) as type utils.mailConfig in argument to utils.StartNewMailer
我是否必须将每个单独的值传递给被调用的函数,或者有更好的方法来实现这一点?
英文:
I have to parse some nested JSON, which translates into a Go type, like this:
type Config struct {
Mail struct {
From string
To string
Password string
}
Summary struct {
Send bool
Interval int
}
}
Now I want to call a function for each key (Mail, Summary), I tried it like this:
utils.StartNewMailer(config.Mail)
The problem is, how do I construct the called function, I tried to mirror the Mail
struct (and called it mailConfig
), since I can't pass an arbitrary struct as an argument.
func StartNewMailer(conf mailConfig){ //...
, but that doesn't work either, I get the following compiler error message:
cannot use config.Mail (type struct { From string; To string; Password string }) as type utils.mailConfig in argument to utils.StartNewMailer
Do I have to pass in every single value to the called function or is there a nicer way to do this?
答案1
得分: 0
utils.mailConfig
字段应该被导出,就像Config
类型中的字面结构字段一样。
type mailConfig struct {
From string
To string
Password string
}
我建议将内部结构声明为它们自己的类型,而不是使用结构字面值。
type Mail struct {
From string
To string
Password string
}
type Summary struct {
Send bool
Interval int
}
type Config struct {
Mail
Summary
}
func StartNewMailer(Mail mailConfig)
英文:
utils.mailConfig
fields should be exported, as in the literal struct field in Config
type.
type mailConfig struct {
From string
To string
Password string
}
I suggest declaring inner structs as types themselves instead of using struct literals.
type Mail struct {
From string
To string
Password string
}
type Summary struct {
Send bool
Interval int
}
type Config struct {
Mail
Summary
}
func StartNewMailer(Mail mailConfig)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论