gpt4 book ai didi

go - 将结构的命名字段传递给其他函数

转载 作者:数据小太阳 更新时间:2023-10-29 03:31:11 24 4
gpt4 key购买 nike

这是我的第一个 golang 程序,而不仅仅是阅读文档,所以请多多包涵。

我的结构如下:-(来自经过解析的 yaml)

type GLBConfig struct {
GLBList []struct {
Failover string `json:"failover" yaml:"failover"`
GLB string `json:"glb" yaml:"glb"`
Pool []struct {
Fqdn string `json:"fqdn" yaml:"fqdn"`
PercentConsidered int `json:"percent_considered" yaml:"percent_considered"`
} `json:"pool" yaml:"pool"`
} `json:"glb_list" yaml:"glb_list"`
}

现在,在我的主函数中,有一个 for 循环处理每个 GLB:-

for _, glb := range config_file.GLBList {
processGLB(glb)
}

接收这种类型的 processGLB 的函数定义是什么?

我尝试这样做,但它不起作用,我想知道为什么。

func processGLB(glb struct{}) {
fmt.Println(glb)
}

./glb_workers.go:42: cannot use glb (type struct { Failover string "json:\"failover\" yaml:\"failover\""; Glb string "json:\"glb\" yaml:\"glb\""; Pool []struct { Fqdn string "json:\"fqdn\" yaml:\"fqdn\""; PercentConsidered int "json:\"percent_considered\" yaml:\"percent_considered\"" } "json:\"pool\" yaml:\"pool\"" }) as type struct {} in argument to processGLB

然后,稍后进行一些谷歌搜索,这有效。

func processGLB(glb interface{}) {
fmt.Println(glb)
}

这样做是个好主意吗? 为什么我必须使用接口(interface)来传递一个名为字段的简单结构?

最后,在 golang 中最优雅/最正确的方法是什么?

编辑:

简单的解决方案是单独定义结构。

type GLBList struct {
Failover string `json:"failover" yaml:"failover"`
GLB string `json:"glb" yaml:"glb"`
Pool []struct {
Fqdn string `json:"fqdn" yaml:"fqdn"`
PercentConsidered int `json:"percent_considered" yaml:"percent_considered"`
} `json:"pool" yaml:"pool"`
}

type GLBConfig struct {
GLBs []GLBList `json:"glb_list" yaml:"glb_list"`
}

然后是函数定义,例如:-

func processGLB(glb GLBList) {
}

最佳答案

您真的应该考虑显式定义结构并重用它。使用支持静态类型的语言的全部意义在于尽可能定义您的类型,它有助于编译器查找错误并生成更快的代码。

此外,如果您想要更紧凑的代码,您可以使用 anonymous fields 的概念。 ,尽管我认为这不是最好的方案。

关于go - 将结构的命名字段传递给其他函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33852394/

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