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

    评论

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥15 Stata 面板数据模型选择
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏