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 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件