繁体   English   中英

使用Go在Appengine /数据存储区中设置为零的值

[英]Nilable value in appengine/datastore using Go

数据存储区支持的类型列表不包含指针类型( https://cloud.google.com/appengine/docs/go/datastore/reference )。 那我怎样才能代表一个有时可能为零的值? 例如,在以下结构中,我需要DailyValuePercent为零,以明确表示该值丢失。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM