猿问

条件(动态)结构标签

我正在尝试在 Go 中解析一些 xml 文档。为此,我需要定义一些结构,而我的结构标签取决于特定条件。


想象一下下面的代码(即使我知道它不会工作)


if someCondition {

    type MyType struct {

        // some common fields

        Date    []string `xml:"value"`

    }

} else {

    type MyType struct {

        // some common fields

        Date    []string `xml:"anotherValue"`

    }

}


var t MyType

// do the unmarshalling ...

问题是这两个结构有很多共同的字段。唯一的区别在于其中一个字段,我想防止重复。我怎么解决这个问题?


牧羊人nacy
浏览 128回答 3
3回答

慕码人8056858

您使用不同的类型来解组。基本上,您编写了两次解组代码,然后运行第一个版本或第二个版本。对此没有动态解决方案。

神不在的星期二

最简单的可能是处理所有可能的字段并进行一些后处理。例如:type MyType struct {    DateField1    []string `xml:"value"`    DateField2    []string `xml:"anotherValue"`}// After parsing, you have two options:// Option 1: re-assign one field onto another:if !someCondition {    parsed.DateField1 = parsed.DateField2    parsed.DateField2 = nil}// Option 2: use the above as an intermediate struct, the final being:type MyFinalType struct {    Date    []string `xml:"value"`}if someCondition {    final.Date = parsed.DateField1} else {    final.Date = parsed.DateField2}注意:如果消息差异很大,您可能需要完全不同的类型进行解析。后处理可以从其中任何一个生成最终结构。

慕尼黑8549860

如前所述,您必须复制该字段。问题是重复应该存在于何处。如果它只是多个字段中的一个,一种选择是使用嵌入和字段阴影:type MyType struct {    Date    []string `xml:"value"`    // many other fields}然后当Date使用其他字段名称时:type MyOtherType struct {    MyType // Embed the original type for all other fields    Date     []string `xml:"anotherValue"`}然后在解组之后MyOtherType,很容易将Date值移动到原始结构中:type data MyOtherTypeerr := json.Unmarshal(..., &data)data.MyType.Date = data.Datereturn data.MyType // will of MyType, and fully populated请注意,这仅适用于解组。如果您还需要编组这些数据,可以使用类似的技巧,但围绕它的机制必须从本质上颠倒过来。
随时随地看视频慕课网APP

相关分类

Go
我要回答