Gravy
Gravy

Reputation: 12445

Custom Time Marshall Unmarshall

I have a MysqlTime struct with it's own marshall and unmarshall.

type MysqlTime struct {
    time.Time
}

const MYSQL_TIME_FORMAT = "2006-01-02 15:04:05"

func (t *MysqlTime) UnmarshalJSON(b []byte) (err error) {
    s := strings.Trim(string(b), `\`)
    if s == "null" {
        t.Time = time.Time{}
        return
    }
    t.Time, err = time.Parse(MYSQL_TIME_FORMAT, s)
    return
}

func (t *MysqlTime) MarshalJSON() ([]byte, error) {
    if t.Time.UnixNano() == nilTime {
        return []byte("null"), nil
    }
    return []byte(fmt.Sprintf(`"%s"`, t.Time.Format(MYSQL_TIME_FORMAT))), nil
}

var nilTime = (time.Time{}).UnixNano()

func (t *MysqlTime) IsSet() bool {
    return t.UnixNano() != nilTime
}

Now I wish to use it...

type Foo struct {
    Time *MysqlTime
}

func main() {

    now := MysqlTime(time.Now())

    foo := Foo{}
    foo.Time = &now
}

Error:

cannot convert now (type time.Time) to type helpers.MysqlTime
cannot take the address of helpers.MysqlTime(now)

Upvotes: 1

Views: 128

Answers (1)

eugenioy
eugenioy

Reputation: 12393

When doing this:

now := MysqlTime(time.Now())

It tries to convert a Time to your MysqlTime type (which throws an error).

Did you mean to actually initialize the inner Time attribute, like so?

now := MysqlTime{time.Now()}

Upvotes: 1

Related Questions