自定义时间的编组和解组

huangapple go评论75阅读模式
英文:

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()}

huangapple
  • 本文由 发表于 2017年6月27日 23:48:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/44784676.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定