我有一个MysqlTime
结构,它有自己的马歇尔和解组。
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
}
现在我想用它......
type Foo struct {
Time *MysqlTime
}
func main() {
now := MysqlTime(time.Now())
foo := Foo{}
foo.Time = &now
}
错误:
cannot convert now (type time.Time) to type helpers.MysqlTime
cannot take the address of helpers.MysqlTime(now)
答案 0 :(得分:1)
这样做时:
now := MysqlTime(time.Now())
它会尝试将Time
转换为您的MysqlTime
类型(会引发错误)。
您是否真的要初始化内部Time
属性,就像这样?
now := MysqlTime{time.Now()}