2015-10-19 76 views
0

的方法,我有一個名爲類型,我需要做做一些JSON unmarshmaling:調用命名類型

type StartTime time.Time 
func (st *StartTime) UnmarshalJSON(b []byte) error {...} 

由於StartTimetime.Time,我認爲我將能夠調用屬於方法到time.Time,如Date()

myStartTime.Date() // myStartTime.Date undefined (type my_package.StartTime has no field or method Date) 

我如何添加方法,以現有的類型,同時保留其原有的方法呢?

+0

見[此答案](http://stackoverflow.com/questions/29397801/whats-該最佳實踐推斷方法/ 29397985#29397985)的例子關於嵌入/不嵌入自定義時間類型之間的區別。 –

回答

4

使用type關鍵字您正在創建一個新類型,因此它將不具有基礎類型的方法。

使用嵌入:

Spec: Struct types報價:

字段或在結構x匿名場的methodf被稱爲促進如果x.f是一個合法的選擇器,表示該字段或方法f

因此,嵌入(匿名)字段的所有方法和字段都會被提升並且可以被引用。

實施例使用它:

type StartTime struct { 
    time.Time 
} 

func main() { 
    s := StartTime{time.Now()} 
    fmt.Println(s.Date()) 
} 

輸出(嘗試在Go Playground):

2009 November 10 
+0

不知道「推廣」功能,謝謝! – Tyler

+1

@Tyler感謝您的編輯。還在Playground上編輯了代碼併發布了新鏈接。 – icza