接口 Go 并不是“传统”的面向对象编程语言,没有类和继承的概念(这不是废话吗)
但是 Go 中有非常灵活的接口 概念,通过接口可以实现很多面向对象的特性。接口提供了一种方式来说明对象的行为:谁能搞定这件事谁就在这里用
接口定义了一组方法(方法集),但是这些方法不包含(实现)代码它们没有被实现(抽象的)。接口里也不包含变量。
通过如下格式定义接口:
1 2 3 4 5 type Namer interface { Method1(param_list) return_type Method2(param_list) return_type ... }
上面的 Namer
是接口类型。
(按照约定,只包含一个方法的)接口名字由方法名+er
后缀组成,例如Printer
, Reader
, Writer
, Loger
, Converter
等等。还有一些不常用的方式,比如 Recoverable
,此时接口名以 able
结尾,或者以 I
开头)(像.NET
或 Java
那样)
Go 的接口都很简单,通常为包含0个,最多3个方法。
不像大多数面向对象编程语言,在 Go 中接口是可以包含值的,一个接口类型的变量或一个接口值:var ai Namer
,ai
是一个多字(multiword)数据结构,它的值是 nil
。本质上是指针,虽然不完全是一回事。指向街口值的指针是非法的,他不仅一点用没有还会导致代码错误。
此处的方法指针表是通过运行时反射能力构建的。
类型(比如结构体)可以实现某个接口的方法集;这个实现可以描述为。该类型的变量上的每一个具体方法所组成的集合,包含了该接口的方法集。实现了 Namer
接口的类型的变量可以赋值给 ai
(即 receiver
的值),方法表指针( method table ptr
)就指向了当前方法的实现。当另一个实现了 Namer
接口类型的变量被赋给 ai
, receiver
的值和方法表指针也会相应改变。
类型不需要显示声明它实现了某个接口:接口被隐式地实现。多个类型可以实现同一个接口。
实现某个接口的类型(除了实现接口方法外)可以有其他的方法
一个类型可以实现多个接口
接口类型可以包含一个实例的引用,该实例的类型实现了此接口(接口是动态类型)
(至此,我已经彻底不会了)
即使接口在类型之后才定义,而这处于不同的包中,被单独编译:只要类型实现了接口中的方法,它就实现了此接口。
所有这些特性使得接口具有很大的灵活性
第一个例子(终于来代码了)
示例interfaces.go
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 package mainimport "fmt" type Shaper interface { Area() float32 }type Square struct { side float32 }func (sq *Square) Area() float32 { return sq.side * sq.side }func main () { sq1 := new (Square) sq1.side = 5 areaIntf := sq1 fmt.Printf("The square has area: %f\n" , sq1.Area()) fmt.Printf("The area of the square is: %f\n" , areaIntf.Area()) }
输出结果
1 2 The square has area: 25.000000 The area of the square is: 25.000000
上面的程序定义了一个结构体 Square
和一个接口 Shaper
,接口还有一个方法 Area()
。
在 main()
方法中创建了一个 Square
的实例。在主程序外边定义了一个接受这类型是 Square
方法的 Area()
,用来计算正方形的面积:结构体 Square
实现了接口 Shaper
(实现是通过*Square)
所以可以将一个 Square
类型的变量赋值给一个接口类型的变量:areaIntf = sq1
。(这里解释一下,是由于我们通过sq1
对 areaIntf
进行赋值,使得 areaIntf
引用了指向Square结构体的实例,且由于Square实现了 shaper
接口,所以它成为了接口变量)
现在接口变量包含一个指向 Square
变量的引用,通过它可以调用 Square
上的方法 Area()
。当然也可以直接在 Square
的实例上调用此方法,但是在接口实例上调用此方法更顺畅,它使此方法更具有一般性。接口变量内包含了接收者实例的值和指向对应方法表的指针。
这是多态 的Go版本,多态是面向对象编程中一个广为人知的概念:根据当前的类型选择正确的方法,或者说:同一种类型在不同实例上似乎表现出不同的行为。
如果 Square
没有实现 Area()
方法,则编译器会给出清晰的错误:
1 2 cannot use sq1 (type *Square) as type Shaper in assignment: *Square does not implement Shaper (missing Area method)
如果 Shaper
有另外一个方法 Perimeter()
,但是 Square
没有实现,即使没有人在 Square
实例上调用这个方法,编译器也会给出上面的错误。
扩展上面的例子,类型 Rectangle
也实现了 Shaper
接口。接着创建一个 Shaper
类型的数组,迭代它的每一个元素并在上面调用 Area()
方法,以此来展示多态行为:
示例interfaces_poly.go
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 36 package mainimport "fmt" type Shaper interface { Area() float32 }type Square sturct { side float32 }func (sq * Square) Area() float32 { return sq.side * sq.side }type Rectangle struct { length, width float32 }func (r * Rectangle) Area() float32 { return r.length * r.width }func main () { r := Rectangle{5 , 10 } q := &Square{5 } shapes := []Shaper{r,q} fmt.Println("Looping through shapes for area ..." ) for n,_ := range shapes{ fmt.Println("Shape details: " , shapes[n]) fmt.Println("Area of this shape is:" , shapes[n].Area()) } }
输出结果
1 2 The square has area: 25.000000 The area of the square is: 25.000000
在调用 shapes[n].Area()
这个时,只知道 shapes[n]
是一个对象,最后他还变成了一个 Squaere
或 Rectangle
对象,并且表现出了相应的行为。
现在开始将看到如何通过接口产生更干净、更简单及更具有扩展性的代码。在11.12.3中将看到在开发中为类型添加新的接口是多么容易。
下面是一个更加具体的例子:有两个类型 stockPosition
和 car
,他们都有一个 getValue()
方法,我们可以定义一个具有此方法的接口 valuable
。接着定义一个使用 valuable
类型作为参数的函数 showValue()
,所有实现了 valuable
接口的类型都可以用这个接口。
示例valuable.go (原始链接404了,可能维护的时候删了,直接看我写的吧)
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 36 37 38 39 40 41 package mainimport "fmt" type stockPosition struct { ticker string sharePrice float32 count float32 }func (s stockPosition) getValue() float32 { return s.sharePrice * s.count }type car struct { make string model string price float32 }func (c car) getValue() float32 { return c.price }type valuable interface { getValue() float32 }func showValue (asset valuable) { fmt.Printf("Value of the asset is %f\n" , asset.getValue()) }func main () { var o valuable = stockPosition{"GOOG" , 577.20 , 4 } showValue(o) o = car{"BMW" , "M3" , 66500 } showValue(o) }
输出结果
1 2 Value of the asset is 2308.800049 Value of the asset is 66500.000000
一个标准库的例子
io
包里有一个接口类型 Reader
:
1 2 3 type Reader interface { Read(p []byte ) (n int , err error ) }
定义变量 r
:var r io.Reader
那么就可以写下面的代码
1 2 3 4 5 6 var r io.Reader r = os.Stdin r = bufio.NewReader(r) r = new (bytes.Buffer) f,_ : os.Open("test.text" ) r = bufio.NewReader(f)
上面 r
右边的类型都实现了 Read()
方法,并且有相同的方法签名,r
的静态类型是 io.Reader
PS:
有的时候,也会以一种稍微不同的方式来使用接口这个词:从某个类型的角度来看,它的接口指的是:它的所有导出方法,只不过没有显式地为这些导出方法额外定一个接口而已。
接口嵌套接口 一个借口可以包含一个或多个其它接口,这相当于直接将这些内嵌接口的方法列举在外层接口中一样。
比如接口 File
包含了 ReadWrite
和 Lock
的所有方法,它还额外有一个 Close()
方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 type ReadWrite interface { Read(b Buffer) bool Write(b Buffer) bool }type Lock interface { Lock() Unlock() }type File interface { ReadWrite Lock Close() }
类型断言:如何检测和转换接口变量的类型 一个接口类型的变量 varI
中可以包含任何类型的值,必须有一种方式来检测它的 动态 类型,即运行时再变量中存储的值的实际类型。在执行过程中动态类型可能会有所不同,但它总是可以分配给接口变量本身的类型。通常我们可以使用 类型断言 来测试在某个时刻 varI
是否包含类型 T
的值:
varI
必须是一个接口变量,否则编译器会报错:invalid type assertion: varI.(T) (non-interface type (type of varI) on left)
。
类型断言可能是无效的,虽然编译器会尽力检查转换是否有效,但是它不可能预见所有可能的情况。如果转换在程序运行时失败就会导致错误发生。更安全的方式是使用以下的类型来进行类型断言:(虽然但是,类型断言好像也确实没说明白是个啥,然后发现下面的代码才是说明类型断言是什么)
1 2 3 4 5 if v, ok := varI.(T); ok { Process(v) return }
如果转换合法,v
是 varI
转换到类型 T
的值,ok
会是 true
;否则 v
是 类型 T
的零值,ok
是 false
,也没有运行时错误发生。
应该总是使用上面的方法来进行类型断言。
多数情况下,我们可能只是想在 if
中测试一下 ok
的值,此时使用以下的方法会是最方便的:
1 2 3 if _, ok := varI.(T); ok { }
示例type_interfaces.go
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 36 37 38 39 40 41 42 package mainimport ( "fmt" "math" )type Square struct { side float32 }type Circle struct { radius float32 }type Shaper interface { Area() float32 }func main () { var areaIntf Shaper sq1 := new (Square) sq1.side = 5 areaIntf = sq1 if t, ok := areaIntf.(*Square); ok { fmt.Printf("The type of areaIntf is: %T\n" , t) } if u, ok := areaIntf.(*Circle); ok { fmt.Printf("The type of areaIntf is: %T\n" , u) } else { fmt.Println("areaIntf does not contain a variable of type Circle" ) } }func (sq *Square) Area() float32 { return sq.side * sq.side }func (ci *Circle) Area() float32 { return ci.radius * ci.radius * math.Pi }
输出结果
1 2 The type of areaIntf is: *main.Square areaIntf does not contain a variable of type Circle
这个程序中定义了一个新的类型 Circle
。该类型也实现了 Shaper
接口。if t, ok := areaIntf.(*Square); ok
测试 areaIntf
里是否有一个包含 *Square
类型的变量,结果是确定的;然后测试它是否包含一个 *Circle
类型的变量,结果是否定的。
PS:
如果忽略 areaIntf.(*Square)
中的 *
,会导致编译错误: impossible type assertion: Square does not implement Shaper (Area method has pointer receiver)
类型判断:type-switch 接口类型的变量也可以使用一种特殊形式的 switch
来检测:type-switch (下面是前一个示例的下半部分,我这里就放完整版代码了)
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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 package mainimport ( "fmt" "math" )type Square struct { side float32 }type Circle struct { radius float32 }type Shaper interface { Area() float32 }func main () { var areaIntf Shaper sq1 := new (Square) sq1.side = 5 areaIntf = sq1 if t, ok := areaIntf.(*Square); ok { fmt.Printf("The type of areaIntf is: %T\n" , t) } if u, ok := areaIntf.(*Circle); ok { fmt.Printf("The type of areaIntf is: %T\n" , u) } else { fmt.Println("areaIntf does not contain a variable of type Circle" ) } switch w := areaIntf.(type ) { case *Square: fmt.Printf("Type Square %T with value %v\n" , w, w) case *Circle: fmt.Printf("Type Circle %T with value %v\n" , w, w) case nil : fmt.Printf("nil value: nothing to check?\n" ) default : fmt.Printf("Unexpected type %T\n" , w) } }func (sq *Square) Area() float32 { return sq.side * sq.side }func (ci *Circle) Area() float32 { return ci.radius * ci.radius * math.Pi }
输出结果
1 2 3 The type of areaIntf is: *main.Square areaIntf does not contain a variable of type Circle Type Square *main.Square with value &{5}
变量 t
得到了 areaIntf
的值和类型,所有 case
语句中列举的类型(nil
除外)都必须实现对于的接口(示例中为 Shaper
),如果被检测的类型没有在 case
语句列举的类型中,就会执行 default
语句。
可以用 type-switch
进行运行时类型分析,但是在 type-switch
不允许有 fallthrough
。
如果仅仅时测试变量的类型,不使用它的值,那么就不需要使用赋值语句,如:
1 2 3 4 5 6 7 8 9 switch areaIntf.(type ) { case *Square: case * Circle: ... default : }
下面的代码片段展示了一个类型分类函数,它有一个可变长度参数,可以时任意类型的数组,会根据数组元素的实际类型执行不同的动作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 func classifier (items ...interface {}) { for i, x := range items { switch x.(type ) { case bool : fmt.Printf("Param #%d is a bool\n" , i) case float64 : fmt.Printf("Param #%d is a float64\n" , i) case int , int64 : fmt.Printf("Param #%d is a int\n" , i) case nil : fmt.Printf("Param #%d is a nil\n" , i) case string : fmt.Printf("Param, #%d is a string\n" , i) default : fmt.Printf("Param #%d is unknown\n" , i) } } }
可以这样调用方法 classifier(13, -14.3, “BELGIUM”, complex(1, 2), nil, false)
。
在处理来自外部的、类型未知的数据师,比如解析诸如JSON或XML编码的数据,类型测试和转换会非常有用。
在后续示例中 12.17 xml.go 在解析XML文档的时候我们就会用到 type-switch