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 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问