2017-06-27 4 views
1

私はMysqlTime構造体を持っています。それ自身のマーシャルとアンマーシャルです。カスタムタイムマーシャル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 
} 

今、私は

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) 

答えて

1

now := MysqlTime(time.Now()) 

をそれはTimeに変換しようとしますあなたのMysqlTimeタイプ(エラーをスローする)。

実際に内部のTime属性を初期化したのですか?

now := MysqlTime{time.Now()} 
関連する問題