Go 语言接口
接口的定义
Go 语言不是一种 “传统” 的面向对象编程语言:它里面没有类和继承的概念。
但是 Go 语言里有非常灵活的接口概念,通过接口可以实现很多面向对象的特性。
接口定义了一组方法(方法集),但是这些方法不包含实现的代码,它们是抽象的,接口里也不能包含变量。
通过如下格式定义接口:
type Namer interface {Method1(param_list) return_typeMethod2(param_list) return_type...}
上面的 Namer 是一个 接口类型。
按照约定,只包含一个方法的接口名字由方法名加 [e]r 后缀组成,例如 Printer、Reader、Writer、Logger、Converter 等等。还有一些不常用的方式(当后缀 er 不合适时),比如 Recoverable,此时接口名以 able 结尾,或者以 I 开头(像 C# 或 Java 中那样)。
Go 语言中的接口都很简短,通常它们会包含 0 个、最多 3 个方法。
不像大多数面向对象编程语言,在 Go 语言中接口可以有值 :var ai Namer,ai 是一个多字(multiword)数据结构,它的值是 nil。它本质上是一个指针,虽然不完全是一回事。指向接口值的指针是非法的,它们不仅一点用也没有,还会导致代码错误。
类型(比如结构体)可以实现某个接口的方法集,这个实现可以描述为:该类型的变量上的每一个具体方法所组成的集合,包含了该接口的方法集。实现了 Namer 接口的类型的变量可以赋值给 ai(即 receiver 的值),方法表指针(method table ptr)就指向了当前的方法实现。当另一个实现了 Namer 接口的类型的变量被赋给 ai,receiver 的值和方法表指针也会相应改变。
类型不需要显式声明它实现了某个接口,接口被隐式地实现。多个类型可以实现同一个接口。
实现某个接口的类型(除了实现接口方法外)可以有其他的方法。
一个类型可以实现多个接口。
接口类型可以包含一个实例的引用, 该实例的类型实现了此接口(接口是动态类型)。即使接口在类型之后才定义,二者处于不同的包中,被单独编译:只要类型实现了接口中的方法,它就实现了此接口。
上面所有这些特性使得接口具有很大的灵活性。
示例 interfaces.go:
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 = 5var areaIntf ShaperareaIntf = sq1// shorter,without separate declaration:// areaIntf := Shaper(sq1)// or even:// areaIntf := sq1fmt.Printf("The square has area: %f\n", areaIntf.Area())}
输出:
The square has area: 25.000000
上面的示例定义了一个结构体 Square 和一个接口 Shaper,接口有一个方法 Area()。
在 main() 方法中创建了一个 Square 的实例。在主程序外边定义了一个接收者类型是 Square 方法的 Area(),用来计算正方形的面积:结构体 Square 实现了接口 Shaper 。
所以可以将一个 Square 类型的变量赋值给一个接口类型的变量:areaIntf = sq1 。
现在接口变量包含一个指向 Square 变量的引用,通过它可以调用 Square 上的方法 Area()。当然也可以直接在 Square 的实例上调用此方法,但是在接口实例上调用此方法可以使此方法更具有一般性。接口变量里包含了接收者实例的值和指向对应方法表的指针。
这是 多态 的 Go 版本,多态是面向对象编程中一个广为人知的概念:根据当前的类型选择正确的方法,或者说:同一种类型在不同的实例上似乎表现出不同的行为。
如果 Square 没有实现 Area()方法,编译器将会给出清晰的错误信息:
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() 方法,以此来展示多态行为:
package mainimport "fmt"type Shaper interface {Area() float32}type Square struct {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, 3} // Area() of Rectangle needs a valueq := &Square{5} // Area() of Square needs a pointer// shapes := []Shaper{Shaper(r), Shaper(q)}// or shortershapes := []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())}}
输出:
Looping through shapes for area ...Shape details: {5 3}Area of this shape is: 15Shape details: &{5}Area of this shape is: 25
在调用 shapes[n].Area() 这个时,只知道 shapes[n] 是一个 Shaper 对象,最后它摇身一变成为了一个 Square 或 Rectangle 对象,并且表现出了相对应的行为。
下面是一个更具体的例子:有两个类型 stockPosition 和 car,它们都有一个 getValue() 方法,我们可以定义一个具有此方法的接口 valuable。接着定义一个使用 valuable 类型作为参数的函数 showValue(),所有实现了 valuable 接口的类型都可以用这个函数。
package mainimport "fmt"type stockPosition struct {ticker stringsharePrice float32count float32}/* method to determine the value of a stock position */func (s stockPosition) getValue() float32 {return s.sharePrice * s.count}type car struct {make stringmodel stringprice float32}/* method to determine the value of a car */func (c car) getValue() float32 {return c.price}/* contract that defines different things that have value */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)}
输出:
Value of the asset is 2308.800049Value of the asset is 66500.000000
下面我们看看标准库 io 包的一个例子,io 包里有一个接口类型 Reader:
type Reader interface {Read(p []byte) (n int, err error)}
定义变量 r: var r io.Reader
那么就可以写如下的代码:
var r io.Readerr = os.Stdin // see 12.1r = bufio.NewReader(r)r = new(bytes.Buffer)f,_ := os.Open("test.txt")r = bufio.NewReader(f)
上面 r 右边的类型都实现了 Read() 方法,并且有相同的方法签名,r的静态类型是 io.Reader。
接口嵌套接口
一个接口可以包含一个或多个其他的接口,这相当于直接将这些内嵌接口的方法列举在外层接口中一样。
比如接口 File 包含了 ReadWrite 和 Lock 的所有方法,它还额外有一个 Close() 方法。
type ReadWrite interface {Read(b Buffer) boolWrite(b Buffer) bool}type Lock interface {Lock()Unlock()}type File interface {ReadWriteLockClose()}
类型断言:如何检测和转换接口变量的类型
一个接口类型的变量 varI 中可以包含任何类型的值,必须有一种方式来检测它的 动态 类型,即运行时在变量中存储的值的实际类型。在执行过程中动态类型可能会有所不同,但是它总是可以分配给接口变量本身的类型。通常我们可以使用 类型断言 来测试在某个时刻 varI 是否包含类型 T的值:
v := varI.(T) // unchecked type assertion
varI 必须是一个接口变量,否则编译器会报错:
invalid type assertion: varI.(T) (non-interface type (type of varI) on left) 。
类型断言可能是无效的,虽然编译器会尽力检查转换是否有效,但是它不可能预见所有的可能性。如果转换在程序运行时失败会导致错误发生。更安全的方式是使用以下形式来进行类型断言:
if v, ok := varI.(T); ok { // 检查类型的断言Process(v)return}// varI 不是 T 类型
如果转换合法,v 是 varI 转换到类型 T 的值,ok 会是 true;否则 v 是类型 T 的零值,ok 是 false,也没有运行时错误发生。
多数情况下,我们可能只是想在 if 中测试一下 ok 的值,此时使用以下的方法会是最方便的:
if _, ok := varI.(T); ok {// ...}
示例 type_interfaces.go:
package mainimport ("fmt""math")type Square struct {side float32}type Circle struct {radius float32}type Shaper interface {Area() float32}func main() {var areaIntf Shapersq1 := new(Square)sq1.side = 5areaIntf = sq1// Is Square the type of areaIntf?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}
输出:
The type of areaIntf is: *main.SquareareaIntf does not contain a variable of type Circle
程序中定义了一个新类型 Circle,它也实现了 Shaper 接口。 if t, ok := areaIntf.(*Square); ok 测试 areaIntf 里是否有一个包含 *Square 类型的变量,结果是 true;然后我们测试它是否包含一个 *Circle 类型的变量,结果是 false。
备注
如果忽略 areaIntf.(*Square)中的 * 号,会导致编译错误:
impossible type assertion: Square does not implement Shaper (Area method has pointer receiver)。
类型判断:type-switch
接口变量的类型也可以使用一种特殊形式的 switch 来检测:type-switch:
switch t := areaIntf.(type) {case *Square:fmt.Printf("Type Square %T with value %v\n", t, t)case *Circle:fmt.Printf("Type Circle %T with value %v\n", t, t)case nil:fmt.Printf("nil value: nothing to check?\n")default:fmt.Printf("Unexpected type %T\n", t)}
输出:
Type Square *main.Square with value &{5}
变量 t 得到了 areaIntf 的值和类型, 所有 case 语句中列举的类型(nil 除外)都必须实现对应的接口(在上例中即 Shaper),如果被检测类型没有在 case 语句列举的类型中,就会执行 default 语句。
可以用 type-switch 进行运行时类型分析,但是在 type-switch 不允许有 fallthrough 。
如果仅仅是测试变量的类型,不用它的值,那么就可以不需要赋值语句,比如:
switch areaIntf.(type) {case *Square:// TODOcase *Circle:// TODO...default:// TODO}
下面的代码片段展示了一个类型分类函数,它有一个可变长度参数,可以是任意类型的数组,它会根据数组元素的实际类型执行不同的动作:
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 编码的数据,类型测试和转换会非常有用。
测试一个值是否实现了某个接口
假定 v 是一个值,然后我们想测试它是否实现了 Stringer 接口,可以这样做:
type Stringer interface {String() string}if sv, ok := v.(Stringer); ok {fmt.Printf("v implements String(): %s\n", sv.String()) // note: sv, not v}
Print 函数就是如此检测类型是否可以打印自身的。
接口是一种契约,实现类型必须满足它,它描述了类型的行为,规定类型可以做什么。接口彻底将类型能做什么,以及如何做分离开来,使得相同接口的变量在不同的时刻表现出不同的行为,这就是多态的本质。
编写参数是接口变量的函数,这使得它们更具有一般性。
使用接口使代码更具有普适性。
标准库里随处可见的接口都使用了这个原则,如果对接口概念没有良好的把握,是不可能理解它是如何构建的。