本教材由知了传课辛苦制作而成,仅供学习使用,请勿用于商业用途!如进行转载请务必注明出处!谢谢!

接口:interface

接口是Go语言中所有数据结构的核心

所有类型都实现了空接口 interface {},空接口可以用来做泛型

可以实现多态

是method的集合,也是一种类型,只有签名,没有具体实现代码

一、接口的定义

type 接口名称 interface { 方法 }

代码示例:

package main import "fmt" type MyInterface interface { IMyAdd() } func MyAdd(i MyInterface) { i.IMyAdd() } type MathOperation struct { } func (m MathOperation) IMyAdd() { fmt.Println("这是运算的add方法") } func main() { mathOpe := MathOperation{} MyAdd(mathOpe) }

二、接口的作用(好处)

1.泛型编程(空接口)

2.隐藏具体实现:只限定方法名称,具体的实现不用管

3.传参:不同的结构体参数

三、iface和eface

1.iface:非空接口

_type *_type:具体类型

inter *interfacetype:具体类型实现的接口类型

type iface struct {
tab *itab
data unsafe.Pointer
}

type itab struct {
inter *interfacetype
_type *_type
hash uint32 // copy of _type.hash. Used for type switches.
_ [4]byte
fun [1]uintptr // variable sized. fun[0]==0 means _type does not implement inter.
}

2.eface:空接口

_type *_type

type eface struct {
_type *_type
data unsafe.Pointer
}

1450人已阅读,今天你学习了吗?

添加新回复