Golang – 将结构体作为参数传递给函数

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

Golang - pass struct as argument to function

问题

我必须解析一些嵌套的JSON,它转换成了一个Go类型,就像这样:

  1. type Config struct {
  2. Mail struct {
  3. From string
  4. To string
  5. Password string
  6. }
  7. Summary struct {
  8. Send bool
  9. Interval int
  10. }
  11. }

现在我想为每个键(Mail、Summary)调用一个函数,我尝试了以下方式:

  1. utils.StartNewMailer(config.Mail)

问题是,我该如何构造被调用的函数?我试图复制Mail结构体(并将其命名为mailConfig),因为我不能将任意结构体作为参数传递。

  1. func StartNewMailer(conf mailConfig) { //...

但这也不起作用,我得到了以下编译器错误信息:

  1. 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:

  1. type Config struct {
  2. Mail struct {
  3. From string
  4. To string
  5. Password string
  6. }
  7. Summary struct {
  8. Send bool
  9. Interval int
  10. }
  11. }

Now I want to call a function for each key (Mail, Summary), I tried it like this:

  1. 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:

  1. 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类型中的字面结构字段一样。

  1. type mailConfig struct {
  2. From string
  3. To string
  4. Password string
  5. }

我建议将内部结构声明为它们自己的类型,而不是使用结构字面值。

  1. type Mail struct {
  2. From string
  3. To string
  4. Password string
  5. }
  6. type Summary struct {
  7. Send bool
  8. Interval int
  9. }
  10. type Config struct {
  11. Mail
  12. Summary
  13. }
  14. func StartNewMailer(Mail mailConfig)
英文:

utils.mailConfig fields should be exported, as in the literal struct field in Config type.

  1. type mailConfig struct {
  2. From string
  3. To string
  4. Password string
  5. }

I suggest declaring inner structs as types themselves instead of using struct literals.

  1. type Mail struct {
  2. From string
  3. To string
  4. Password string
  5. }
  6. type Summary struct {
  7. Send bool
  8. Interval int
  9. }
  10. type Config struct {
  11. Mail
  12. Summary
  13. }
  14. func StartNewMailer(Mail mailConfig)

huangapple
  • 本文由 发表于 2015年5月26日 07:02:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/30447073.html
匿名

发表评论

匿名网友

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

确定