我有一个带有自己的marshall和unmarshall的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)
最佳答案
执行此操作时:
now := MysqlTime(time.Now())
它将尝试将
Time
转换为您的MysqlTime
类型(这将引发错误)。您是要像这样真正初始化内部
Time
属性吗?now := MysqlTime{time.Now()}