golang中type alias的误解

一定看到过这样的定义结构体的方式:

type InnerType struct {
    Name string
    ID int32
}

func (i InnerType) GetName() string {
    return i.Name
}
type OutterType1 struct {
    InnerType
}

这叫embeding struct, 这样做的好处就是可以继承原结构的字段和方法。由于刚入门golang,以之前C++的思想考虑问题时就在想:为什么不直接做type alias?

type OutterType2 InnerType

C/C++中的typedef 作用与关键字type类似,但是真的类似吗?

typedef实际上只是给类型起了一个别名,并没有改变类型相关的任何信息。那么golang中的type关键字与typedef作用相同吗?答案是否定的。实际上OutterType2如果调用方法GetName()的话是无法通过编译的。

原因可以从golang标准中得到:
The declared type does not inherit any methods bound to the existing type, but the method set of an interface type or of elements of a composite type remains unchanged.
就是说golang中使用type关键字做了type alias后的类型继承原类型的所有元素,但是不继承原类型的所有方法。

但是如果非要使用原类型的方法,其实可以做类型转换:

InnerType(outter).GetName()

参考

  1. https://golang.org/ref/spec#Type_declarations
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,200评论 19 139
  • { "Unterminated string literal.": "未终止的字符串文本。", "Identifi...
    一粒沙随风飘摇阅读 10,864评论 0 3
  • "Unterminated string literal.": "未终止的字符串文本。", "Identifier...
    两个心阅读 8,481评论 0 4
  • 1.使用BeautifulSoup库解析网页 from bs4 import BeautifulSoup 2.使用...
    starcloudes阅读 258评论 0 0
  • 青山远走 水横流 何忧? 晴空碧浪 怎抵去意别愁 把万山看遍 叶红 梦里庭院梧桐 ...
    多佛儿阅读 286评论 1 3