dtxa49711 2015-04-18 14:51
浏览 21
已采纳

使用Go在应用引擎/数据存储中的可空值

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条回答 默认 最新

  • dongyan7851 2015-04-18 15:34
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图