一句话说明
接口提供了一种方式来说明对象的行为:如果谁能搞定这件事,它就可以用在这儿。
接口定义了一组方法(方法集),但是这些方法不包含(实现)代码:它们没有被实现(它们是抽象的)。
所以一句话来说,接口是使用方法的抽象
定义:
type Integer int
func (a Integer) Less(b Integer) bool {
return a < b
}
func (a *Integer) Add(b Integer) {
*a += b
}
type LessAdder interface {
Less(b Integer) bool
Add(b Integer)
}
接口赋值,将实例赋值给接口
var a Integer = 1 var b LessAdder = &a
接口查询
var file1 Writer = ...
if file5, ok := file1.(two.IStream); ok {
...
}
Writer接口的实现实例file1,是否实现了 two.IStream 接口,如果实现了则执行代码。
类型查询
在 Go 语言中,还可以更加直截了当地询问接口指向的对象实例的类型。
利用反射也可以进行类型查询,详情可参阅reflect.TypeOf()方法。
var v1 interface{} = ...
switch v := v1.(type) {
case int: // 现在v的类型是int
case string: // 现在v的类型是string
...
}
接口组合
type ReadWriter interface {
Reader
Writer
}
这个接口组合了Reader和Writer两个接口,它完全等同于如下写法:
type ReadWriter interface {
Read(p []byte) (n int, err error)
Write(p []byte) (n int, err error)
}
空接口 Any类型
由于Go语言中任何对象实例都满足空接口interface{},所以interface{}看起来像是可以指向任何对象的 Any 类型,如下:
var v1 interface{} = 1 // 将int类型赋值给interface{}
var v2 interface{} = "abc" // 将string类型赋值给interface{}
var v3 interface{} = &v2 // 将*interface{}类型赋值给interface{}
var v4 interface{} = struct{ X int }{1}
var v5 interface{} = &struct{ X int }{1}
当函数可以接受任意的对象实例时,我们会将其声明为interface{},最典型的例子是标准库 fmt 中 PrintXXX 系列的函数,例如:
传入参数是 可变数量的 任意类型。
func Printf(fmt string, args ...interface{})
func Println(args ...interface{})
空接口
空接口中没有任何方法,表示为 interface{},由于空接口没有任何方法,因此可以理解为所有类型默认实现了此接口。
类型判定
可以使用语法 i.(T) 获取变量i中T类型的值,以此来判断传入的类型是否正确
s := i.(int) // 获取变量 i 中 int 类型的数据,若 i 不是 int, 则 panic v, ok := i.(int) // 用这种方式避免 panic
可以配合 switch 实现类型判断
func findType(i interface{}) {
switch i.(type) {
case string:
fmt.Printf("I am a string and my value is %s
", i.(string))
case int:
fmt.Printf("I am an int and my value is %d
", i.(int))
default:
fmt.Printf("Unknown type
")
}
}
将类型与接口进行比较。如果我们有一个类型,并且该类型实现了一个接口,则可以将该类型与其实现的接口进行比较。
type Describer interface {
Describe()
}
type Person struct {
name string
age int
}
func (p Person) Describe() {
fmt.Printf("%s is %d years old", p.name, p.age)
}
func findType(i interface{}) {
switch v := i.(type) {
case Describer:
v.Describe()
default:
fmt.Printf("unknown type
")
}
}
通过嵌入接口,实现继承的功能
type SalaryCalculator interface {
DisplaySalary()
}
type LeaveCalculator interface {
CalculateLeavesLeft() int
}
type EmployeeOperations interface {
SalaryCalculator
LeaveCalculator
}
type Employee struct {
firstName string
lastName string
basicPay int
pf int
totalLeaves int
leavesTaken int
}
// Employee 实现了 DisplaySalary 和 CalculateLeavesLeft 两个接口,也就默认实现了 EmployeeOperations 接口
func (e Employee) DisplaySalary() {
fmt.Printf("%s %s has salary $%d", e.firstName, e.lastName, (e.basicPay e.pf))
}
func (e Employee) CalculateLeavesLeft() int {
return e.totalLeaves - e.leavesTaken
}
func main() {
e := Employee {
firstName: "Naveen",
lastName: "Ramanathan",
basicPay: 5000,
pf: 200,
totalLeaves: 30,
leavesTaken: 5,
}
// 此处可以说 Employee 实现了 EmployeeOperations接口
var empOp EmployeeOperations = e
empOp.DisplaySalary()
fmt.Println("
Leaves left =", empOp.CalculateLeavesLeft())
}
接口的 0 值
接口的零值为nil。nil接口具有其基础值和具体类型(如nil)
type Describer interface {
Describe()
}
func main() {
var d1 Describer
if d1 == nil {
// 此处输出 d1 is nil and has type <nil> value <nil>
fmt.Printf("d1 is nil and has type %T value %v
", d1, d1)
}
}