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)
}

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"
- 2 回答
- 0 關(guān)注
- 180 瀏覽
添加回答
舉報