英文:
Calling method of named type
问题
我有一个命名类型,我需要创建它来进行一些JSON解组:
type StartTime time.Time
func (st *StartTime) UnmarshalJSON(b []byte) error {...}
由于StartTime
是一个time.Time
类型,我以为我可以调用属于time.Time
的方法,比如Date()
:
myStartTime.Date() // myStartTime.Date未定义(类型my_package.StartTime没有字段或方法Date)
我如何在现有类型上添加方法,同时保留其原始方法?
英文:
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?
答案1
得分: 5
使用type
关键字创建一个新类型,因此它不会具有底层类型的方法。
使用嵌入:
type StartTime struct {
time.Time
}
引用自规范:结构类型:
在结构体
x
中,匿名字段的字段或方法f
如果x.f
是合法的选择器,表示该字段或方法f
,则称为_提升_。
因此,嵌入字段的所有方法和字段都会被提升,并且可以引用。
以下是一个使用示例:
type StartTime struct {
time.Time
}
func main() {
s := StartTime{time.Now()}
fmt.Println(s.Date())
}
输出结果(在Go Playground上尝试):
2009 November 10
英文:
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 struct x
is called promoted if x.f
is a legal selector that denotes that field or method f
.
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论