英文:
Nilable value in appengine/datastore using Go
问题
Datastore不支持指针类型(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用作数据存储的字段类型,那么如何表示可选值呢?
英文:
The list of supported types by datastore doesn't contain pointer types (https://cloud.google.com/appengine/docs/go/datastore/reference).
How then can I represent a value that can and sometimes should be nil?
For example in the following structure I need the DailyValuePercent
to be nilable to explicitly say that the value is missing.
type NutritionFact struct {
Name string `datastore:",noindex" json:"name"`
DailyValuePercent int `datastore:",noindex" json:"dailyValuePercent"`
}
Since I can't use *int as the field type for datastore then how to represent an optional value?
答案1
得分: 0
要么将整数存储为字符串(空字符串表示无值),要么使用复合类型,例如:
type NillableInt struct {
i int
isNil bool // 或者如果您想要不同的默认语义,则为 isNotNil bool
}
根据您的性能和内存使用要求进行调整。
如果您希望您的代码处理整数指针但在数据存储中保留 nil 值,请像这样定义您的结构:
type NutritionFact struct {
Name string `datastore:",noindex" json:"name"`
DailyValuePercent int `datastore:"-"`
}
并实现 PropertyLoadSaver 接口,在其中保存/加载一个整数值和一个 isNil 布尔值。
英文:
Either store your ints as strings (with empty string => no value) or use a composite type like:
type NillableInt struct {
i int
isNil bool // or isNotNil bool if you want different default semantics
}
Adapt to your performance vs. memory usage requirements.
If you want your code to deal with int pointers but persist nil values in the datastore, define your struct like this:
type NutritionFact struct {
Name string `datastore:",noindex" json:"name"`
DailyValuePercent int `datastore:"-"`
}
And implement the PropertyLoadSaver interface where you will save/load an int value and a isNil boolean.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论