19.2 接口嵌入

一个接口可以包含一个或多个其他的接口,但是在接口内不能嵌入结构体,也不能嵌入接口自身,否则编译会出错。

下面这两种嵌入接口自身的方式都不能编译通过:

// 编译错误:invalid recursive type Bad
type Bad interface {
	Bad
}
// 编译错误:invalid recursive type Bad2
type Bad1 interface {
	Bad2
}
type Bad2 interface {
	Bad1
}

比如下面的接口 File 包含了 ReadWrite 和 Lock 的所有方法,它还额外有一个 Close() 方法。接口的嵌入方式和结构体的嵌入方式语法上差不多,直接写接口名即可。

type ReadWrite interface {
    Read(b Buffer) bool
    Write(b Buffer) bool
}
type Lock interface {
    Lock()
    Unlock()
}
type File interface {
    ReadWrite
    Lock
    Close()
}
下一节:前面我们可以把实现了某个接口的类型值保存在接口变量中,但反过来某个接口变量属于哪个类型呢?如何检测接口变量的类型呢?这就是类型断言(Type Assertion)的作用。