【问题标题】:Nilable value in appengine/datastore using Go使用 Go 在 appengine/datastore 中的可取值
【发布时间】:2015-04-18 14:51:32
【问题描述】:

数据存储支持的类型列表不包含指针类型 (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 作为数据存储的字段类型,那么如何表示可选值?

【问题讨论】:

    标签: google-app-engine go google-cloud-datastore


    【解决方案1】:

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

    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 接口,您将在其中保存/加载一个 int 值和一个 isNil 布尔值。

    【讨论】:

    • 我猜第三个选项是在我的结构中包含 *int 并使用 PropertyLoadSaver 有条件地保存它,对吧?还值得注意的是,存储布尔值(就像我所做的那样)会占用大量数据存储空间,结果可能会很昂贵。
    猜你喜欢
    • 1970-01-01
    • 2016-07-11
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    相关资源
    最近更新 更多