亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

條件(動態)結構標簽

條件(動態)結構標簽

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 關注
  • 157 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號