调用方法的命名类型 [英] Calling method of named type

查看:88
本文介绍了调用方法的命名类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 类型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 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

这篇关于调用方法的命名类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆