简体   繁体   中英

Assign to nil pointer in receiver method

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?

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM