前言
本文将解释Golang中interface的定义,用法,注意事项,希望对大家的工作学习提供借鉴与帮助。
定义
interface定义
参考Golang Spec文档(https://golang.org/ref/spec),interface定义如下:
An interface type specifies a method set called its interface. A variable of interface type can store a value of any type with a method set that is any superset of the interface. Such a type is said to implement the interface. The value of an uninitialized variable of interface type is nil.
意思是说:接口类型指定了一个方法集(method set),这个方法集称为该接口类型的接口。接口类型T的变量可以保存任意类型X的值,只要该类型X的方法集满足是该接口类型T的超集。这样的类型X可以说实现了接口类型T。未初始化的接口类型变量的值为nil。
Go语言里面,声明一个接口类型需要使用type关键字、接口类型名称、interface关键字和一组有{}括起来的方法声明(method specification),这些方法声明只有方法名、参数和返回值,不需要方法体。
如下我们声明了Bird接口类型:
type Bird interface {
Twitter(name string) string
Fly(height int) bool
}
在一个接口类型中,每个方法(method)必须名字非空且唯一(unique & non-blank)
Go语言没有继承的概念,那如果需要实现继承的效果怎么办?Go的方法是嵌入。
接口类型支持嵌入(embedding)来实现继承的效果。
一个接口类型T可以使用接口类型E的名字,放在方法声明的位置。称为将接口类型E嵌入到接口类型T中,这样会将接口类型E的全部方法(公开的,私有的)添加到接口类型T。
例如:
type ReadWriter interface {
Read(b Buffer) bool
Write(b Buffer) bool
}
type Locker interface {
Lock()
Unlock()
}
type File interface {
ReadWriter // same as adding the methods of ReadWriter
Locker // same as adding the methods of Locker
Close()
}
type LockedFile interface {
Locker
File // illegal: Lock, Unlock not unique
Lock() // illegal: Lock not unique
}
在java中,通过类来实现接口。一个类需要在声明通过implements显示说明实现哪些接口,并在类的方法中实现所有的接口方法。Go语言没有类,也没有implements,如何来实现一个接口呢?这里就体现了Go与别不同的地方了。
首先,Go语言没有类但是有struct,通过struct来定义模型结构和方法。
其次,Go语言实现一个接口并不需要显示声明,而是只要你实现了接口中的所有方法就认为你实现了这个接口。这称之为Duck typing。
method set定义
Golang Spec中对于Method Set的定义如下:
https://golang.org/ref/spec#Method_sets
A type may have a method set associated with it. The method set of an interface type is its interface. The method set of any other type
T
consists of all met