在Go中,接口interface其实和其他语言的接口意思也没什么区别。interface理解其为一种类型的规范或者约定。一种类型是不是“实现”了一个接口呢?就看这种类型是不是实现了接口中定义的所有方法。
1 接口的定义和使用。
比如
1
2
3
4
5
|
type I interface {
Get() int
Put( int )
} |
这段话就定义了一个接口,它包含两个函数Get和Put
好了,我的一个接口实现了这个接口:
1
2
3
4
5
6
7
8
|
type S struct {val int }
func ( this *S) Get int {
return this .val
} func ( this *S)Put(v int ) {
this .val = v
} |
这个结构S就是实现了接口I
2 空接口
对于空接口interface{} 其实和泛型的概念很像。任何类型都实现了空接口。
下面举个例子:
一个函数实现这样的功能:
以任何对象作为参数,如果这个对象是实现了接口I,那么就调用接口I的Get方法
很多语言都是这样的逻辑:
1
2
3
4
5
6
|
function g(obj){ if (obj is I) {
return (I)obj.Get()
}
} |
Go中是这样实现的:
1
2
3
4
|
func g(any interface {}) int {
return any.(I).Get()
} |
这里的any.(I)是不是很语义化?“任何实现了I接口的对象”
3 Go中interface的写法:
下面看几个interface的例子:
1
2
3
4
|
func SomeFunction(w interface {Write( string )}){
w.Write( "pizza" )
} |
这个例子中,直接将interface定义在参数中,很特别…
1
2
3
4
5
6
|
func weirdFunc( i int ) interface {} {
if i == 0 {
return "zero"
}
return i;
} |
这里例子中,由于有可能返回string,也有可能返回int,因此将返回值设置成为interface,这个在Go的package包中会大量见到。
本文转自轩脉刃博客园博客,原文链接:http://www.cnblogs.com/yjf512/archive/2012/06/09/2543628.html,如需转载请自行联系原作者