douzi2778 2014-11-18 11:34
浏览 43
已采纳

从结构图调用结构

Hi I am trying something like the following example.

My background as a PHP Developer (I know!) is giving me a hard time on this. I've read the Laws of reflection and other sources, but this is over my head. The approach i am using is probably wrong... and hope someone can point me in the right direction.

The use of this in a concrete way is that the version 01 or 02 or 03 is comming from an external Parameter, based on that, I need to get the appropriate struct and populate it with database values.

package V01
type Struct1 struct{
    Field1 string
    Field2 string
}

type Struct2 struct{
    Field1 string
    Field2 string
}

package V02
type Struct1 struct{
    Field1 string
    Field2 string
    ExtraField1 string
}

type Struct2 struct{
    Field1 string
    Field2 string
    ExtraField2 string
    ExtraField3 string
}

var VStructs = map[string]map[string]interface{}{
    "01": map[string]interface{}{
        "Struct1": V01.Struct1{},
        "Struct2": V01.Struct2{},
    },
    "02": map[string]interface{}{
        "Struct1": V02.Struct1{},
        "Struct2": V02.Struct2{},
    }, 
    "03" : map[string]interface{}{
        "Struct1": V01.Struct1{},
        "Struct2": V02.Struct2{},
    }, 
}

 // I get the struct fieldnames and so on.
 fmt.Printf("%+v
", VStructs["01"]["Struct1"] ) 

 // I cannot access any of the fields though because it is an interface
 fmt.Println( VStructs["01"]["Struct1"].Field1 ) // PANIC! 

 // Type Switching is not working either since the version can be variable.
 s := VStructs["01"]["Struct1"].Field1 
 switch x := s.(type) {
 case reflect.Struct: // PANIC! reflect.Struct (type reflect.Kind) is not a type
    fmt.Println("I am an struct")
 default:
    fmt.Println("I am an no struct")
 }

So maybe can show me an appropriate way of doing this. Or maybe an wrapper function to return the right struct... no clue at this point.

Hope it is clear, and will elaborate more if asked to.

  • 写回答

2条回答 默认 最新

  • douhuilin1152 2014-11-19 20:55
    关注

    Okay, since the question was probably in conflict with the way golang is used to work.

    I have written an package to serve my needs :

    Based on the selected version (In the URL or the Header, whatever you like) we retrieve an map of structs. We now can select the actual struct we need, set some values and finally send it back to the screen OR send it over to the DB (In my case gorp).

    The Package can be found here https://github.com/donseba/contractor/

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

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line