go的匿名组合

golang也提供了继承机制,但采用组合的文法,所以称为匿名组合。与其余语言不一样, golang很清晰地展现出类的内存布局是怎样的。golang

一  非指针方式的组合函数

 1)基本语法布局

 

type base struct{
	//成员变量
}

func(b *base) 函数名(参数列表)(返回值列表){
	//函数体
}

//派生类
type derived struct{
	base
	//成员变量
}

func (b *derived) 函数名(参数列表)(返回值列表){
	//函数体
}

 

2)继承规则spa

 在派生类没有改写基类的成员方法时,相应的成员方法被继承。指针

        派生类能够直接调用基类的成员方法,譬如基类有个成员方法为Base.Func(),那么Derived.Func()等同于Derived.Base.Func()blog

        假若派生类的成员方法名与基类的成员方法名相同,那么基类方法将被覆盖或叫隐藏,譬如基类和派生类都有成员方法Func(),那么Derived.Func()将只能调用派生类的Func()方法,若是要调用基类版本,能够经过Derived.Base.Func()来调用。继承

举例以下:内存

 

package main

import "fmt"

type Base struct{
	//成员变量
}

func(b *Base) Func1(){

	fmt.Println("Base.Func1 was invoked1")

}

func(b *Base) Func2(){

	fmt.Println("Base.Func2 was invoked1")

}

//派生类
type Derived struct{
	Base
	//成员变量
}

func (d *Derived) Func2(){
	fmt.Println("Derived.Func2() was invoked!")
}


func (d *Derived) Func3(){
	fmt.Println("Derived.Func3() was invoked!")
}

func main(){
	d:=&Derived{}
	d.Func1()
	d.Base.Func1()
	d.Func2()
	d.Base.Func2()
	d.Func3()
}

 

 

二  指针组合模式class

基本语法:import

/ 基类
type Base struct {
    // 成员变量
}

func (b *Base) 函数名(参数列表) (返回值列表) {
    // 函数体
}

// 派生类
type Derived struct {
    *Base
    // 成员变量
}

func (b *Derived) 函数名(参数列表) (返回值列表) {
    // 函数体
}
相关文章
相关标签/搜索