英文:
Custom Time Marshall Unmarshall
问题
我有一个名为MysqlTime
的结构体,它有自己的编组(marshal)和解组(unmarshal)方法。
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
}
错误信息:
无法将now(类型为time.Time)转换为helpers.MysqlTime类型
无法获取helpers.MysqlTime(now)的地址
英文:
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)
答案1
得分: 1
当进行以下操作时:
now := MysqlTime(time.Now())
它试图将一个Time
类型转换为你的MysqlTime
类型(这会引发错误)。
你是不是真的想要初始化内部的Time
属性,像这样?
now := MysqlTime{time.Now()}
英文:
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()}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论