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

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

如何在 Golang 的 Google Datastore 中忽略結(jié)構(gòu)中的零值?

如何在 Golang 的 Google Datastore 中忽略結(jié)構(gòu)中的零值?

Go
回首憶惘然 2021-11-22 15:32:42
我正在嘗試使用 Google Datastore 通過 Go 存儲數(shù)據(jù)。由于EndDate是可選字段,并且不想在該字段中存儲零值。如果我為時間字段設(shè)置指針,Google Datastore 將發(fā)送錯誤消息 -datastore: unsupported struct field type: *time.Time如何忽略結(jié)構(gòu)中的零值字段?type Event struct {    StartDate time.Time `datastore:"start_date,noindex" json:"startDate"`    EndDate   time.Time `datastore:"end_date,noindex" json:"endDate"`}
查看完整描述

2 回答

?
躍然一笑

TA貢獻(xiàn)1826條經(jīng)驗(yàn) 獲得超6個贊

默認(rèn)保存機(jī)制不處理可選字段。一個字段要么一直保存,要么從不保存。沒有“僅在其價值不等于某物時才保存”之類的東西。


“可選保存的屬性”被視為自定義行為、自定義保存機(jī)制,因此必須手動實(shí)現(xiàn)。Go 的方法是PropertyLoadSaver在你的結(jié)構(gòu)上實(shí)現(xiàn)接口。在這里,我提出了 2 種不同的方法來實(shí)現(xiàn)這一目標(biāo):


手動保存字段

這是一個如何通過手動保存字段(并排除EndDate它是否為零值)來執(zhí)行此操作的示例:


type Event struct {

    StartDate time.Time `datastore:"start_date,noindex" json:"startDate"`

    EndDate   time.Time `datastore:"end_date,noindex" json:"endDate"`

}


func (e *Event) Save(c chan<- datastore.Property) error {

    defer close(c)

    // Always save StartDate:

    c <- datastore.Property{Name:"start_date", Value:e.StartDate, NoIndex: true}


    // Only save EndDate if not zero value:

    if !e.EndDate.IsZero() {

        c <- datastore.Property{Name:"end_date", Value:e.EndDate, NoIndex: true}

    }

    return nil

}


func (e *Event) Load(c chan<- datastore.Property) error {

    // No change required in loading, call default implementation:

    return datastore.LoadStruct(e, c)

}

與另一個結(jié)構(gòu)

這是使用另一個結(jié)構(gòu)的另一種方法。在Load()實(shí)施永遠(yuǎn)是一樣的,唯一的Save()不同:


func (e *Event) Save(c chan<- datastore.Property) error {

    if !e.EndDate.IsZero() {

        // If EndDate is not zero, save as usual:

        return datastore.SaveStruct(e, c)

    }


    // Else we need a struct without the EndDate field:

    s := struct{ StartDate time.Time `datastore:"start_date,noindex"` }{e.StartDate}

    // Which now can be saved using the default saving mechanism:

    return datastore.SaveStruct(&s, c)

}


查看完整回答
反對 回復(fù) 2021-11-22
?
繁星點(diǎn)點(diǎn)滴滴

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

在字段標(biāo)簽中使用省略。來自文檔:https : //golang.org/pkg/encoding/json/

結(jié)構(gòu)值編碼為 JSON 對象。每個導(dǎo)出的結(jié)構(gòu)字段都成為對象的成員,除非

  • 該字段的標(biāo)簽是“-”,或

  • 該字段為空,其標(biāo)簽指定了“omitempty”選項(xiàng)。

字段整數(shù) json:"myName,omitempty"


查看完整回答
反對 回復(fù) 2021-11-22
  • 2 回答
  • 0 關(guān)注
  • 180 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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