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 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗