Struct 从结构映射调用结构

Struct 从结构映射调用结构,struct,go,Struct,Go,嗨,我正在尝试下面的例子 我作为一名PHP开发人员的背景(我知道!)让我在这方面遇到了困难。 我读过《反思法则》和其他资料,但这太离谱了。我使用的方法可能是错误的。。。希望有人能给我指出正确的方向 它的具体用途是,版本01、02或03来自外部参数,基于此,我需要获得适当的结构并用数据库值填充它 package V01 type Struct1 struct{ Field1 string Field2 string } type Struct2 struct{ Field

嗨,我正在尝试下面的例子

我作为一名PHP开发人员的背景(我知道!)让我在这方面遇到了困难。 我读过《反思法则》和其他资料,但这太离谱了。我使用的方法可能是错误的。。。希望有人能给我指出正确的方向

它的具体用途是,版本01、02或03来自外部参数,基于此,我需要获得适当的结构并用数据库值填充它

package V01
type Struct1 struct{
    Field1 string
    Field2 string
}

type Struct2 struct{
    Field1 string
    Field2 string
}




也许你能给我一个合适的方法。或者使用包装函数返回正确的结构。。。在这一点上没有线索


希望它是清楚的,如果被要求的话,会详细说明。

您不能以这种方式访问地图中的结构,因为可能没有结构。在您的示例中,
VStructs[“foo”][“bar”].Field1是什么?您将无法知道它是否真的是映射中的空结构,或者什么都没有,而映射访问只是为该类型返回了一个空值。您应该做的是明确检查:

v, ok := VStructs["01"]["Struct1"]
if !ok {
    // Handle the case of the missing struct.
}
// It is also a good practice to check type assertions.
s, ok := v.(V01.Struct1)
if !ok {
    // Handle the case when v is not V01.Struct1.
}
f = s.Field1

好吧,因为这个问题可能与golang的工作方式有冲突

我已经写了一个包来满足我的需要:

根据所选版本(在URL或标题中,无论您喜欢什么),我们检索结构的映射。现在我们可以选择我们需要的实际结构,设置一些值,最后将其发送回屏幕或发送到DB(在我的例子中是gorp)


这个包可以在这里找到

谢谢你的回复,但是通过你的例子,我发现
类型接口{}没有字段或方法字段1
@DonSeba,我没有注意到你那里有一个
接口{}
。编辑答案以反映这一点。这里的问题是“V01.Struct1”可能是“V02.Struct1”。。很抱歉也许我在尝试一些动态的东西,和golang一起..@DonSeba在围棋中这样做很好。在这种情况下,您需要一个接口或为所有这些结构定义一个接口来实现并用这个新的接口类型替换
接口{}
。您应该在类型开关中使用类型名称,而不是
reflect.Kind
值。也就是说,它应该是
案例V01。结构:
等,而不是
案例反映。结构:
@Ainar-G,谢谢,但是版本V01、V02、V03是可变的,因此,这并不是一个真正的选项,特别是当每个版本中有大约50个结构时……那么你需要为所有这些结构定义一个接口来实现。你能给我一个例子,上面的结构可以用作接口吗?在编辑之后,你现在问的是一个完全不同的问题。最初的问题是关于结构图的。我建议再问一个问题,因为有太多的细节需要考虑。
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\n", 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")
 }
v, ok := VStructs["01"]["Struct1"]
if !ok {
    // Handle the case of the missing struct.
}
// It is also a good practice to check type assertions.
s, ok := v.(V01.Struct1)
if !ok {
    // Handle the case when v is not V01.Struct1.
}
f = s.Field1