为了账号安全,请及时绑定邮箱和手机立即绑定

条件(动态)结构标签

条件(动态)结构标签

Go
牧羊人nacy 2023-06-19 16:59:06
我正在尝试在 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 ...问题是这两个结构有很多共同的字段。唯一的区别在于其中一个字段,我想防止重复。我怎么解决这个问题?
查看完整描述

3 回答

?
慕码人8056858

TA贡献1803条经验 获得超6个赞

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



查看完整回答
反对 回复 2023-06-19
?
神不在的星期二

TA贡献1963条经验 获得超6个赞

最简单的可能是处理所有可能的字段并进行一些后处理。


例如:


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

}

注意:如果消息差异很大,您可能需要完全不同的类型进行解析。后处理可以从其中任何一个生成最终结构。


查看完整回答
反对 回复 2023-06-19
?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

如前所述,您必须复制该字段。问题是重复应该存在于何处。


如果它只是多个字段中的一个,一种选择是使用嵌入和字段阴影:


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 MyOtherType

err := json.Unmarshal(..., &data)

data.MyType.Date = data.Date

return data.MyType // will of MyType, and fully populated

请注意,这仅适用于解组。如果您还需要编组这些数据,可以使用类似的技巧,但围绕它的机制必须从本质上颠倒过来。


查看完整回答
反对 回复 2023-06-19
  • 3 回答
  • 0 关注
  • 92 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信