Go 接口
Go语言中的接口
一、Go中接口的概念
Go 语言提供了另外一种数据类型即接口,它把所有的具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了这个接口。
接口结构:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
/* 定义接口 */ type interface_name interface { method_name1 [return_type] method_name2 [return_type] method_name3 [return_type] ... method_namen [return_type] } /* 定义结构体 */ type struct_name struct { /* variables */ } /* 实现接口方法 */ func (struct_name_variable struct_name) method_name1() [return_type] { /* 方法实现 */ } ... func (struct_name_variable struct_name) method_namen() [return_type] { /* 方法实现*/ } |
二、举个例子
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 |
package main import ( "fmt" ) type Phone interface { call() } type NokiaPhone struct { } func (nokiaPhone NokiaPhone) call() { fmt.Println("I am Nokia, I can call you!") } type IPhone struct { } func (iPhone IPhone) call() { fmt.Println("I am iPhone, I can call you!") } func main() { var iphone Phone = new(IPhone) var nokiaphone Phone = new(NokiaPhone) iphone.call() nokiaphone.call() } |
其实go中的接口和java中的很像。
如果是在java中,我们就先会创建一个接口(Phone),定义一个方法(call()),然后写两个实现类去实现这个接口(IPhone/NokiaPhone)。在实例化这个接口之后(Phone iphone = new IPhone()/Phone nokiaphone = new NokiaPhone()),我们就可以调用接口中的方法(iphone.call()/nokiaphone.call())。
在go中,我们依然先创建一个接口,定义一个方法,
1 2 3 |
type Phone interface { call() } |
写两个struct去实现接口
1 2 3 4 5 |
type IPhone struct { } type NokiaPhone struct { } |
然后写出接口方法(这里要特别注意格式,struct和方法名都需要注意)
1 2 3 4 5 6 7 |
func (nokiaPhone NokiaPhone) call() { fmt.Println("I am Nokia, I can call you!") } func (iPhone IPhone) call() { fmt.Println("I am iPhone, I can call you!") } |
实例化接口
1 2 3 |
var iphone Phone = new(IPhone) var nokiaphone Phone = new(NokiaPhone) |
之后就可以调用接口方法,输出如下:
1 2 |
I am Nokia, I can call you! I am iPhone, I can call you! |
三、总结
go中有很多使用接口的地方,需要多用,多体会。