2016-12-13 30 views
0

我想編碼我的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)

回答

1

你需要你的類型轉換回time.Time有訪問其方法。命名類型不會「繼承」其基礎類型的方法(要這樣做,您需要embedding)。

而且,正如個人喜好的問題,我傾向於首選fmt.Sprintf("%v", i)strconv.FormatInt(i, 10)甚至strconv.Itoa(i)。老實說不知哪個更快,但fmt版本似乎更容易閱讀,個人。