Tyl*_*ler 1 methods inheritance go
我有一个命名类型,我需要使用它来进行一些 JSON 解组:
type StartTime time.Time
func (st *StartTime) UnmarshalJSON(b []byte) error {...}
Run Code Online (Sandbox Code Playgroud)
由于StartTime是 a time.Time,我认为我可以调用属于 的方法time.Time,例如Date():
myStartTime.Date() // myStartTime.Date undefined (type my_package.StartTime has no field or method Date)
Run Code Online (Sandbox Code Playgroud)
如何向现有类型添加方法,同时保留其原始方法?
使用type关键字您正在创建一个新类型,因此它将不具有基础类型的方法。
使用嵌入:
type StartTime struct {
time.Time
}
Run Code Online (Sandbox Code Playgroud)
引用规范:结构类型:
如果结构体中匿名字段的字段或方法 是表示该字段或方法的合法选择器,则该字段或方法被称为提升。
fxx.ff
所以嵌入(匿名)字段的所有方法和字段都被提升并且可以被引用。
使用它的示例:
type StartTime struct {
time.Time
}
func main() {
s := StartTime{time.Now()}
fmt.Println(s.Date())
}
Run Code Online (Sandbox Code Playgroud)
输出(在Go Playground上尝试):
2009 November 10
Run Code Online (Sandbox Code Playgroud)