第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何在 Go 中將自定義格式的時(shí)間序列化為 xml 或從 xml 序列化?

如何在 Go 中將自定義格式的時(shí)間序列化為 xml 或從 xml 序列化?

Go
慕標(biāo)琳琳 2021-10-18 11:04:33
將日期時(shí)間序列化為 xml 時(shí),如何使其使用自定義時(shí)間格式?
查看完整描述

2 回答

?
萬千封印

TA貢獻(xiàn)1891條經(jīng)驗(yàn) 獲得超3個(gè)贊

就像您使用 JSON實(shí)現(xiàn)json.Marshaler和json.Unmarshaler執(zhí)行此操作一樣(在 StackOverflow 和互聯(lián)網(wǎng)上有很多關(guān)于此的帖子);一種方法是實(shí)現(xiàn)實(shí)現(xiàn)encoding.TextMarshaler和的自定義時(shí)間類型encoding.TextUnmarshaler。


這些接口encoding/xml在對項(xiàng)目進(jìn)行編碼時(shí)使用(在首先檢查更具體的xml.Marshaler或xml.Unmarshaler接口之后,但是后來的那些必須自己進(jìn)行完整的 XML 編碼)。


例如類似(完整示例Go Playground):


const fixedFormat = "Mon Jan 02 2006"


type myTime1 struct {

    time.Time

}


func (m myTime1) MarshalText() ([]byte, error) {

    text := m.Time.Format(fixedFormat)

    return []byte(text), nil

}

func (m *myTime1) UnmarshalText(text []byte) error {

    t, err := time.Parse(fixedFormat, string(text))

    if err == nil {

        m.Time = t

    }

    return err

}

或者


type myTime2 time.Time


func (m myTime2) MarshalText() ([]byte, error) {

    text := time.Time(m2).Format(fixedFormat)

    return []byte(text), nil

}

func (m *myTime2) UnmarshalText(text []byte) error {

    t, err := time.Parse(fixedFormat, string(text))

    if err == nil {

        *m = myTime2(t)

    }

    return err

}

這些中的任何一個(gè)都可以用來代替time.Time與 xml (un) marshalling 一起使用的更大數(shù)據(jù)結(jié)構(gòu)的一部分。例如:


type Foo struct {

    Date1 myTime1 `xml:"date1"`

    Date2 myTime2 `xml:"date2"`

}

這些自定義時(shí)間類型定義方式的不同會(huì)改變您將它們與常規(guī)time.Time值一起使用的方式。例如


m1 := myTime1{time.Now()}

fmt.Println(m1)

if m1.Before(time.Now()) {}

t1 := m1.Time

// compared to:

m2 := myTime2(time.Now())

fmt.Println(time.Time(m2))

if time.Time(m2).Before(time.Now()) {}

t2 := time.Time(m2)


查看完整回答
反對 回復(fù) 2021-10-18
  • 2 回答
  • 0 關(guān)注
  • 215 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)