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.