GO的接口
1、接口的简单实现
GO的接口没有java里implement这种东西,而是应用了duck-type的形式,所以GO中interface和类不是绑定的。所谓duck-type就是说你看到一个东西长着脚蹼和扁嘴像鸭子,所以认为他是鸭子。2333这解释是不是有点傻,总之就是说看着像什么就认为是什么。
看下代码:
type helloworld interface {//定义helloworld接口
white()
}
type programmer struct {//定义programmer类
}
func (p *programmer)white() {//调用接口helloworld
fmt.Println("hello world")
}
func main() {
a:=programmer{}
a.white()
}
输出:
hello world
2、GO接口的特点与多态
GO接口只能包含方法标签,不像java可以包含常量。GO中interface是指针类型。下面是一个简单的多态实现:
type programming interface {
white() string
}
type python struct {
}
func (python)white()string {
return "print('hello world!')"
}
type java struct {
}
func (java)white()string {
return "System.Out.Println(\"hello world!\")"
}
func program_whiter(p programming) {
fmt.Println(p.white())
}
func main() {
jar:=&java{}
py:=new(python)
program_whiter(jar)
program_whiter(py)
}
输出:
System.Out.Println("hello world!")
print('hello world!')
注意接口是指针类型,传到program_whiter()中的一定要是对象的指针