1. 继承和组合的区别
-
继承
如果一个struct嵌套了另一个匿名结构体,那么这个结构可以直接访问匿名结构体的方法,从而实现继承 -
组合
如果一个struct嵌套了另一个【有名】的结构体,那么这个模式叫做组合 -
多重继承
如果一个struct嵌套了多个匿名结构体,那么这个结构可以直接访问多个匿名结构体的方法,从而实现多重继承
2. 组合示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
type Plugin interface{ GetName() Func1() } type PluginName string func (p *Plugin) GetName(){ return name } type plugin struct{ name PluginName args int[] } type (*plugin) Func1(){ } type (*plugin) GetName(){ } |
这里plugin结构体需要设置一个GetName()函数来实现Plugin接口,其中参数name PluginName只是作为一个结构体存在,组合到plugin结构体中.
3. 继承示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
type Plugin interface{ GetName() Func1() } type PluginName string func (p *Plugin) GetName(){ return name } type plugin struct{ PluginName args int[] } func (*plugin) Func1(){ } //实例化时,直接使用该匿名结构体名称; p:=plugin{ PluginName:PluginName("plugin1"), args: make(int[],0), } |
这里plugin结构体中存在匿名结构体PluginName,继承了匿名结构体PluginName中GetName函数.符合接口Plugin规范,不需要额外设置GetName函数;
这里如果匿名结构体是其他包中结构,例如package1.PluginName, 其定义和实例化如下:
1 2 3 4 5 6 7 8 9 |
type plugin struct{ package1.PluginName args int[] } p:=plugin{ PluginName:PluginName("plugin1"), args: make(int[],0), } |
4. 多重继承示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
struct嵌套了多个匿名结构体,那么这个结构可以直接访问多个匿名结构体的方法,从而实现多重继承 package main import ( "fmt" "time" ) type Car struct { Name string Age int } func (c *Car) Set(name string, age int) { c.Name = name c.Age = age } type Car2 struct { Name string } //Go有匿名字段特性 type Train struct { Car Car2 createTime time.Time //count int 正常写法,Go的特性可以写成 int } //给Train加方法,t指定接受变量的名字,变量可以叫this,t,p func (t *Train) Set(age int) { t.int = age } func main() { var train Train train.int = 300 //这里用的匿名字段写法,给Age赋值 //(&train).Set(1000) train.Car.Set("huas", 100 ) train.Car.Name = "test" //这里Name必须得指定结构体 fmt.Println(train) } |
微信赞赏
支付宝赞赏
type (*plugin) Func1(){
}
有这种写法??
不好意思,已修正