doujiao4710 2015-11-22 06:51
浏览 33
已采纳

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

This is my first golang program rather than just reading docs so please bear with me.

I've a structure like:- (comes from a parsed 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"`
}

Now, in my main function, there's a for loop which does processing of each GLB:-

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

What will be the function definition of processGLB to receive this type?

I tried doing this but it doesn't work and I would like to know why.

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

Then, some googling later, this works.

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

Is it a good idea to do this? Why do I have to use interfaces to pass a simple structure named field?

In the end, what's the most elegant/right way to do this in golang?

EDIT:

Simple solution was to define the structure separately.

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

And then a function definition like:-

func processGLB(glb GLBList) {
}
  • 写回答

2条回答 默认 最新

  • dpgkg42484 2015-11-22 07:44
    关注

    You should really consider define the struct explicitly and reuse it. The all point of using a langauge with support for static typing is to define your types whenever you can, it helps the compiler to find bugs and produce a faster code.

    Also, if you would like to have a more compact code you can use the concept of anonymous fields, although I don't think that is the best scenario for this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)