调用方法的命名类型 [英] Calling method of named type
问题描述
类型StartTime time.Time
func(st * StartTime)UnmarshalJSON(b [] byte)错误{...}
既然 StartTime
是一个 time.Time
,我想我可以调用属于 time.Time
,例如 Date()
:
myStartTime.Date()// myStartTime.Date未定义(类型my_package.StartTime没有字段或方法日期)
如何在保留原始方法的同时将方法添加到现有类型?
使用类型
关键字创建一个新类型,因此它将不具有基础类型的方法。
使用嵌入:
类型StartTime结构{
time.Time
}
从规范:结构类型:
一个字段或方法
f
的一个如果xf
是一个合法选择符,则称 结构x
中的匿名字段为该字段或方法f
。
因此,所有的方法和字段嵌入式(匿名)字段被提升并可被引用。
使用它的示例:
键入StartTime struct {
time.Time
}
func main(){
s:= StartTime {time.Now()}
fmt.Println(s.Date())
}
输出它在去游乐场):
2009年11月10日
I have a named type, which I needed to make to do some JSON unmarshmaling:
type StartTime time.Time
func (st *StartTime) UnmarshalJSON(b []byte) error {...}
Since StartTime
is a time.Time
, I thought that I would be able to call methods that belong to time.Time
, such as Date()
:
myStartTime.Date() // myStartTime.Date undefined (type my_package.StartTime has no field or method Date)
How can I add methods to an existing type, while preserving its original methods?
Using the type
keyword you are creating a new type and as such it will not have the methods of the underlying type.
Use embedding:
type StartTime struct {
time.Time
}
Quoting from the Spec: Struct types:
A field or method
f
of an anonymous field in a structx
is called promoted ifx.f
is a legal selector that denotes that field or methodf
.
So all the methods and fields of the embedded (anonymous) fields are promoted and can be referred to.
Example using it:
type StartTime struct {
time.Time
}
func main() {
s := StartTime{time.Now()}
fmt.Println(s.Date())
}
Output (try it on the Go Playground):
2009 November 10
这篇关于调用方法的命名类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!