一定看到过这样的定义结构体的方式:
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()