gpt4 book ai didi

function - Golang - 将结构作为参数传递给函数

转载 作者:IT王子 更新时间:2023-10-29 02:23:58 26 4
gpt4 key购买 nike

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

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(type struct { From string; To string; Password string })作为类型 utils.mailConfig

我是否必须将每个值都传递给被调用函数,或者是否有更好的方法来做到这一点?

最佳答案

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)

关于function - Golang - 将结构作为参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30447073/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com