美文网首页
12 接口interface

12 接口interface

作者: haokeed | 来源:发表于2017-07-28 17:17 被阅读0次

接口是一个或多个方法签名的集合
只要某个类型拥有该接口的所有方法签名,即算实现该接口,无需显示
声明实现了哪个接口,这称为 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

相关文章

  • 12 接口interface

    接口是一个或多个方法签名的集合只要某个类型拥有该接口的所有方法签名,即算实现该接口,无需显示声明实现了哪个接口,这...

  • 接口

    interface 接口 implements 类实现接口 public interface 接口名{ 接口的成员...

  • 学习TypeScript 接口

    TypeScript 接口定义 interface interface_name {} 实例 联合类型和接口 接口...

  • Day12_14

    一.接口的使用 interface implements package Day12_14_01; public...

  • java萌新入门之事件监听

    1.接口 1.1 接口的定义 定义接口的关键字:interface 格式: public interface 接口...

  • 2020-07-23(接口)

    1,接口特点 * a:接口用关键字interface表示, interface 接口名 {} * b:类实现接口用...

  • 2020-06-21接口

    接口 接口的特点 接口用关键字interface修饰:public interface 接口名{} 类实现接口用i...

  • java中的接口

    接口的特点: A:接口用关键字interface表示;格式:interface 接口名{}B:类实现接口用imp...

  • Java 接口(interface)

    接口用关键字interface表示格式:interface 接口名 {} 类实现接口用implements表示格式...

  • Java基础-接口

    1.接口的特点: A:接口用关键字interface表示 interface 接口名 {}B:类实现接口用i...

网友评论

      本文标题:12 接口interface

      本文链接:https://www.haomeiwen.com/subject/kakflxtx.html