2017-06-27 3 views
1

Ich habe eine MysqlTime Struktur mit eigenen Marshall und unmarshall.Custom Time Marshall 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 
} 

Nun wünsche ich, es zu benutzen ...

type Foo struct { 
    Time *MysqlTime 
} 

func main() { 

    now := MysqlTime(time.Now()) 

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

Fehler:

now := MysqlTime(time.Now()) 

Es wird versucht, einen Time zu konvertieren:

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

Antwort

1

Wenn dies zu tun Ihre MysqlTime Typ (was einen Fehler auslöst).

Meinen Sie eigentlich das innere Time Attribut zu initialisieren, so?

now := MysqlTime{time.Now()}