我想編碼我的time.Time
字段作爲數字Unix時間,我寧願不爲每個結構實現自定義MarshalJSON函數,因爲我有很多很多的結構。作爲Unix時間的編組時間字段
所以,我試圖定義一個類型別名爲這樣:
type Timestamp time.Time
並在其上實現MarshalJSON像這樣:
func (t Timestamp) MarshalJSON() ([]byte, error) {
return []byte(strconv.FormatInt(t.Unix(), 10)), nil
}
但是,這給了我一個t.Unix undefined (type Timestamp has no field or method Unix)
,這不對我有意義。不應該Timestamp
'繼承'(我知道這可能是錯誤的術語)time.Time
的所有功能?
我也使用類型斷言,像這樣嘗試:
strconv.FormatInt(t.(time.Time).Unix(), 10)
但也失敗了,抱怨無效類型斷言:invalid type assertion: t.(time.Time) (non-interface type Timestamp on left)