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