[Go语言]从Docker源码学习Go——Interfaces
Interface定义:type Namer interface {
Method1(param_list) return_type
Method2(param_list) return_type
...
}
注:
1. interface中不能包含变量
2. 一个类型不用显式去定义实现某个接口,只要包含所有interface中定义的方法,这个类型就默认实现了这个接口
3. 多个类型可以实现相同的接口
4. 一个类型实现接口的同时,还可以定义属于自己的方法
5. 一个类型可以实现多个接口
嵌套的interface
type ReadWrite interface {
Read(b Buffer) bool
Write(b Buffer) bool
}
type Lock interface {
Lock()
Unlock()
}
type File interface {
ReadWrite
Lock
Close()
}
这样File会包含ReadWrite和Lock中所有的方法
判断interface类型
v := varI.(T)
//varI must be an interface variable.
实例
package lemon
type Shaper interface {
Area() float32
}
type Square struct {
Side float32
}
func (sq *Square) Area() float32 {
return sq.Side * sq.Side
}
//use in main func.
func showInterfaceUsage() {
sq1 := new(lemon.Square)
sq1.Side = 5
var areaIntf lemon.Shaper
areaIntf = sq1
if v, ok := areaIntf.(*lemon.Square); ok {
fmt.Printf("The square has area: %f\n", v.Area())
}
}
注意:方法的定义中传的type为指针,判断时也要传指针。
switch areaIntf.(type) {
case *lemon.Square:
fmt.Printf("The square area is %f\n", areaIntf.Area())
default:
fmt.Printf("The default type")
}
也可以直接通过方法interface.(type)来获得接口的类型
判断类型是否实现了接口
...待续
页:
[1]