12 接口interface

2017-07-28  本文已影响0人  haokeed

接口是一个或多个方法签名的集合
只要某个类型拥有该接口的所有方法签名,即算实现该接口,无需显示
声明实现了哪个接口,这称为 Structural Typing
接口只有方法声明,没有实现,没有数据字段
接口可以匿名嵌入其它接口,或嵌入到结构中
将对象赋值给接口时,会发生拷贝,而接口内部存储的是指向这个
复制品的指针,既无法修改复制品的状态,也无法获取指针
只有当接口存储的类型和对象都为nil时,接口才等于nil
接口调用不会做receiver的自动转换
接口同样支持匿名字段方法
接口也可实现类似OOP中的多态
空接口可以作为任何类型数据的容器

type USB interface {
Name() string
Connect()
}

type PhoneConnecter struct {
name string
}

func (pc PhoneConnecter) Name() string{
return pc.name
}

func (pc PhoneConnecter) Connect() {
fmt.Println("connect:", pc.name)
}

func Disconnect(usb Usb){
fmt.Println("Disconnected.")
}

func main {
var a USB
a = PhoneConnecter{"PhoneConnecter"}
a.Connect()
}

--end

嵌入接口
type USB interface {
Name() string
Connecter
}

type Connecter interface {
Connect()
}

type PhoneConnecter struct {
name string
}

func (pc PhoneConnecter) Name() string{
return pc.name
}

func (pc PhoneConnecter) Connect() {
fmt.Println("connect:", pc.name)
}

func Disconnect(usb Usb){
if pc, ok := us.(PhoneConnecter); ok {
fmt.Println("Disconnected.", pc.name)
}
fmt.Println("Unknown decive.")
}

func main {
var a USB
a = PhoneConnecter{"PhoneConnecter"}
a.Connect()
}

类型断言

通过类型断言的ok pattern可以判断接口中的数据类型
使用type switch则可针对空接口进行比较全面的类型判断

接口转换

可以将拥有超集的接口转换为子集的接口

延伸阅读

评: 为什么我不喜欢Go语言式的接口
http://www.ituring.com.cn/article/37642

上一篇 下一篇

猜你喜欢

热点阅读