Golang-将结构作为参数传递给函数 [英] Golang - pass struct as argument to function

查看:67
本文介绍了Golang-将结构作为参数传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须解析一些嵌套的JSON,将其转换为Go类型,如下所示:

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
               }
}

现在我想为每个键(邮件,摘要)调用一个函数,我这样尝试:utils.StartNewMailer(config.Mail)问题是,我该如何构造被调用的函数,我试图镜像 Mail 结构(并称为 mailConfig ),因为我不能像这样传递任意结构一个论点.
func StartNewMailer(conf mailConfig){//...,但这也不起作用,我收到以下编译器错误消息:不能在utils.StartNewMailer的参数中将config.Mail(类型struct {从字符串;到字符串;密码字符串})用作utils.mailConfig.
我是否必须将每个单个值都传递给被调用的函数,或者有更好的方法来做到这一点?

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?

推荐答案

utils.mailConfig 字段应该导出,就像 Config 类型的文字struct字段一样.

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)

这篇关于Golang-将结构作为参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆