Table of Contents

接口 Interface


简单介绍(摘自菜鸟教程)

接口的特点

隐式实现:

接口类型变量:

零值接口:

空接口:

接口的常见用法

  1. 多态:不同类型实现同一接口,实现多态行为。
  2. 解耦:通过接口定义依赖关系,降低模块之间的耦合。
  3. 泛化:使用空接口 interface{} 表示任意类型。

演示

package main
 
import (
	"fmt"
	"math"
)
 
// 「Go 的接口设计简单却功能强大,是实现多态和解耦的重要工具」
 
// 接口:定义操作
type Shape interface {
	Area() float64
}
 
// 结构体:定义数据
type Circle struct {
	Radius float64
}
 
// 在Circle上定义Area操作
// 在Circle定义了所有的Shape的函数后,就相当于Circle实现了接口Shape
// 这种函数叫作「方法」
// c叫作方法的接收器(receiver)
func (c Circle) Area() float64 {
	return math.Pi * c.Radius * c.Radius
}
 
func printStr(t interface{}) {
	// 类型断言:确定t是string类型,获取其string形式的原始值
	if v, success := t.(string); success {
		fmt.Println("String:", v)
	} else {
		fmt.Print("Not a string")
 
		// 类型选择(这里有点没看懂)
		switch value := t.(type) {
		case int:
			fmt.Print(" (Int: ", value, ")")
		}
		fmt.Println()
	}
 
}
 
// 读取接口
type Reader interface {
	Read() string
}
 
// 写入接口
type Writer interface {
	Write(content string)
}
 
// 将两个接口组合起来
type ReadWriter interface {
	// 这里不是定义函数了,而是引入其他的接口
	Reader
	Writer
}
 
func main() {
	// 定义数据
	c := Circle{Radius: 5}
	// 接口变量可以存储实现了接口的类型
	var s Shape = c
	fmt.Println("Area: ", s.Area())
 
	// 空接口 interface{} 是 Go 的特殊接口,表示所有类型的超集
	// 所有类型都实现了 interface{},所以它可以存储任何类型
	var t interface{} = "content"
	printStr(t)
	printStr(1)
 
}