doude4924 2017-03-09 09:28
浏览 50
已采纳

在接收器方法中分配给nil指针

I'm trying to use a time.Time structure in a structure that will be encoded/decoded with JSON. The time.Time attributes should not be included if they aren't set (omitempty tag), so to be able to do so I will have to use a pointer to the time.Time object.

I have defined a type for the time.Time structure so I easily can create receiver functions format the time when the JSON is encoded and decoded etc.

See the code here: https://play.golang.org/p/e81xzA-dzz

So in my main structure (the structure that actually will be encoded) I will do something like this:

type EncodeThis struct {
   Str string `json:"str,omitempty"`
   Date *jWDate `json:"date,omitempty"`
}

The problem is that the pointer may be nil, when trying to decode the value, so if you look at my code at the Go playground, you can see that I'm trying to (using double pointers) to set the address of the receiver if its nil. See method "Set" and "swap".

But, this doesnt seem to work. The program doesn't fail or anything, but the "EncodeThis" struct will not contain a reference to this new address. Any idea for a fix for this?

  • 写回答

1条回答 默认 最新

  • dso89762 2017-03-09 10:24
    关注

    Wrap your date object with a struct containing a pointer to time.Time object.

    // JWDate: Numeric date value
    type jWDate struct {
        date *time.Time
    }
    
    func (jwd *jWDate) Set(t *time.Time) {
        if jwd.date == nil {
            jwd.date = t
        }
    }
    

    If you need to have access to time.Time methods from jWDate struct you can embed it. With embedded type you still have ease access to an object's pointer:

    // JWDate: Numeric date value
    type jWDate struct {
        *time.Time // Embedded `time.Time` type pointer, not just an attribute
    }
    
    func (jwd *jWDate) Set(t *time.Time) {
        if jwd.Time == nil {
            jwd.Time = t
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 模电中二极管,三极管和电容的应用
  • ¥15 关于模型导入UNITY的.FBX: Check external application preferences.警告。
  • ¥15 气象网格数据与卫星轨道数据如何匹配
  • ¥100 java ee ssm项目 悬赏,感兴趣直接联系我
  • ¥15 微软账户问题不小心注销了好像
  • ¥15 x264库中预测模式字IPM、运动向量差MVD、量化后的DCT系数的位置
  • ¥15 curl 命令调用正常,程序调用报 java.net.ConnectException: connection refused
  • ¥20 关于web前端如何播放二次加密m3u8视频的问题
  • ¥15 使用百度地图api 位置函数报错?
  • ¥15 metamask如何添加TRON自定义网络