在面向对象编程中(OOP)接口定义对象的一系列行为,具体对象实现接口的行为。在golang中,接口就是一组方法签名,如果某个类型实现了该接口的全部方法,这个类型就实现了该接口,是该接口的实现。
 在golang中接口定义示例如下:
type MyInterface interface {
	SayHello()
	GetAge() int
}
 
MyInterfaceSayHelloGetAge 
type Person struct {
	age int
	name string
}
func (p Person)SayHello(){
	fmt.Println("hello ",p.name)
}
func (p Person)GetAge() int{
	return p.age
}
 
PersonMyInterface 
	var myInterFace MyInterface
	myInterFace = Person{age:20,name:"Leo"}
	myInterFace.SayHello()
	myInterFace.GetAge()
 
空接口
golang中的空接口,类似于java中的Object超级父类。golang中空皆苦没有任何方法,任意类型都是空接口的实现,空接口定义如下:
type EmptyInterface interface {
	
}
 
EmptyInterface 
	var empty EmptyInterface
	empty = Person{age:20,name:"empty"}
 
接口对象类型转换
如果我们声明了一个接口类型,但是实际指向是一个对象,我们可以通过如下几种方式进行接口和对象类型的转换:
 1.
	if realType,ok := empty.(Person); ok{
		fmt.Println("type is Person ",realType)
	} else if realType,ok := empty.(Animal) ;ok{
		fmt.Println("type is Animal",realType)
	}
 
这种方式可以借助if else进行多个类型的判断
 2.
	switch realType2 := empty.(type) {
	case Person :
		fmt.Println("type is Person",realType2)
	case Animal :
		fmt.Println("type is Animal",realType2)
	}
 
继承
在golang中,采用匿名结构体字段来模拟继承关系。
type Person struct {
	name string
	age int
	sex string
}
func (Person) SayHello(){
	fmt.Println("this is from Person")
}
type Student struct {
	Person
	school string
}
func main() {
	stu := Student{school:"middle"}
	stu.name = "leo"
	stu.age = 30
	fmt.Print(stu.name)
	stu.SayHello()
}
 
StudentPerson 
需要注意的是,结构体嵌套时,可能存在相同的成员名,成员重名可能导致成员名冲突:
type A struct {
	a int
	b string
}
type B struct {
	a int
	b string
}
type C struct {
	A
	B
}
	c := C{}
	c.A.a = 1
	c.A.b = "a"
	c.B.a = 2
	c.B.b = "b"
	
	// 这里会提示a名字冲突
	fmt.Println(c.a)