appengine/datastore 中的 Nilable 值使用 Go

Nilable value in appengine/datastore using Go

数据存储支持的类型列表不包含指针类型 (https://cloud.google.com/appengine/docs/go/datastore/reference)。 那么我如何表示一个可以而且有时应该为零的值呢? 例如,在下面的结构中,我需要 DailyValuePercent 为 nilable 以明确表示缺少该值。

type NutritionFact struct {
    Name                string  `datastore:",noindex" json:"name"`
    DailyValuePercent   int     `datastore:",noindex" json:"dailyValuePercent"`
}

既然我不能使用 *int 作为数据存储的字段类型,那么如何表示可选值?

将您的整数存储为字符串(空字符串 => 无值)或使用复合类型,例如:

type NillableInt struct {
    i     int
    isNil bool  // or isNotNil bool if you want different default semantics
}

适应您的性能与内存使用要求。

如果您希望您的代码处理 int 指针但在数据存储中保留 nil 值,请像这样定义您的结构:

type NutritionFact struct {
       Name                string  `datastore:",noindex" json:"name"`
       DailyValuePercent   int `datastore:"-"`
}

并实现 PropertyLoadSaver 接口,您将在其中 save/load 一个 int 值和一个 isNil 布尔值。