Go 传递结构';将命名字段添加到其他函数
这是我的第一个Go 传递结构';将命名字段添加到其他函数,go,Go,这是我的第一个golang程序,而不仅仅是阅读文档,所以请耐心等待 我有一个类似:-(来自解析的yaml)的结构 现在,在我的主函数中,有一个for循环,它处理每个GLB:- for _, glb := range config_file.GLBList { processGLB(glb) } 接收此类型的processGLB的函数定义是什么? 我尝试过这样做,但不起作用,我想知道原因。 func processGLB(glb struct{}) { fmt.Println(g
golang
程序,而不仅仅是阅读文档,所以请耐心等待
我有一个类似:-(来自解析的yaml)的结构
现在,在我的主函数中,有一个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)
}
这样做是个好主意吗为什么我必须使用接口来传递名为field的简单结构?
最后,在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) {
}
GLBList定义为结构的数组。在go中,没有所谓的struct{}。所有go类型都实现空接口,因此可以使用to pass struct(在本例中,struct没有名称)空接口。对于更多的细节 ,您应该确实考虑显式定义结构并重用它。使用支持静态类型的langauge的要点是尽可能地定义类型,它可以帮助编译器找到bug并生成更快的代码
另外,如果你想有一个更紧凑的代码,你可以使用的概念,虽然我不认为这是最好的方案 那么,为了使用每个
结构,我定义了一个单独的结构?对我来说,这似乎有很多重复的代码。你先定义一个结构,然后定义一个数组。就像您在代码中所做的那样:struct A{}struct B{[]x A}我已经更新了答案,以获得解决方案。谢谢
func processGLB(glb GLBList) {
}