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

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

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)

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

Go模板:如何将array[]string打印到 :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定