调用命名类型的方法

huangapple go评论90阅读模式
英文:

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

huangapple
  • 本文由 发表于 2015年10月19日 16:33:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/33209953.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定