dongmei6426 2017-01-24 18:25
浏览 576

如何从Golang的嵌套结构中获取值

Very new to statically typed languages, so I have this complex struct I'm Unmarshalling

type MyStruc1 struct {
    Property1 uint16 `json:property1`
    Property2 struct {
        Sub2Property1 string `json:sub2property1`
        Sub2Property2 uint16 `json:sub2property2`
        Sub2Property3 struct {
            SubSub2Property1 string `json:subsub2property1`
            SubSub2Property2 string `json:subsub2property1`
        } `json:sub2property3`
    } `json:property2`
    Property3 struct {
        Sub3Property1 string `json:sub3property1`
        Sub3Property2 uint16 `json:sub3property2`
        Sub3Property3 struct {
            SubSub3Property1 string `json:subsub3property1`
            SubSub3Property2 string `json:subsub3property1`
        } `json:sub3peroperty3`
    } `json:property3`
    Property4 string `json:property4`
}

How do i write a function or struct method to accept any one of these arrays and return the value from MyStruct1? Is this possible?

strArray1 := []string{"Property2", "Sub2Property3", "SubSub2Property1"}

strArray2 := []string{"Property3", "Sub3Property1"}

strArray3 := []string{"Property4"}

strArray4 := []string{"Property1"}

Thank you ahead of time with any replies

  • 写回答

1条回答

  • dqg95034 2017-01-24 19:50
    关注

    You can with reflect

    func FieldBySlice(strct interface{}, fields []string) interface{} {
        val := reflect.ValueOf(strct)
        for _, field := range fields {
            val = val.FieldByName(field)
        }
        return val.Interface()
    }
    

    This code works, but you will use it only if very much necessary. It's ugly and not recommended. Try to think different, Go is not scripting, dynamic language

    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题