go 速学 - 13 - Interface

mrseasons · · 1970 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

目录

摘要

定义接口,实现接口,使用接口,作为参数的接口,if 和 switch 中的接口,类型转换,嵌入接口,空接口

interface

概念

  • 只要某个类型拥有该接口的所有方法签名,即算实现该接口,无需显式声明实现哪个接口
  • 接口只有方法声明,无实现,无字段
  • 当接口存储的类型和对象都为 nil 时,接口才为 nil
  • 接口调用不会做 receiver 的自动转换,即指针只能传指针
  • 空接口可以作为任何类型数据的容器

定义接口

type Usb interface {
    getName() string
    connect()
}

实现接口

只要实现接口的所有方法就算是实现了该接口

type PhoneConnector struct {
    name string
}
//PhoneConnector类型实现 Usb 接口
func (pc PhoneConnector) getName() string {
    return pc.name
}
func (pc PhoneConnector) connect() {
    fmt.Println(pc.name, "connect")
}

使用接口

var pc Usb
pc = PhoneConnector{name: "phoneConnector"}
pc.connect() //phoneConnector connect

作为参数的接口

只能使用该接口定义的方法

func disconnect(u Usb) {
    fmt.Print(u.getName())
    fmt.Println(" disconnect")
}
disconnect(pc) //phoneConnector disconnect

通过 if 进行类型匹配

func disconnect2(u Usb) {
    if c, matched := u.(PhoneConnector); matched {
        fmt.Print(c.getName())
    } else {
        fmt.Print("unknown")
    }
    fmt.Println(" disconnect2")
}
disconnect2(pc) //phoneConnector disconnect2

通过 switch 进行类型匹配

func test(u Usb) {
    switch t := s.(type) {
    case PhoneConnector:
        fmt.Println("is PhoneConnector", t)
    default:
        fmt.Println("unkown type", t)
    }
}
test(pc) //is PhoneConnector {phoneConnector}

接口类型转换

只能向上转换,调用父接口的方法

var u Usb
pc2 := PhoneConnector{name: "pc2"}
u = Usb(pc2)
u.connect() //pc2 connect

嵌入接口

type Linker interface {
    link()
}
type DynamicLinker interface {
    getName() string
    Linker
}

空接口

由于没有任何方法,意味着任何类型都实现了此接口

type Empty interface{}

对空接口进行类型匹配

func test(s interface{}) {
    switch t := s.(type) {
    case PhoneConnector:
        fmt.Println("is PhoneConnector", t)
    default:
        fmt.Println("unkown type", t)
    }
}

nil 接口

当接口存储的类型和对象都为nil时,接口才为nil

var e interface{}
fmt.Println(e == nil) //true

var p *int = nil
e = p
fmt.Println(e == nil) //false,接口类型为指针

有疑问加站长微信联系(非本文作者)

本文来自:CSDN博客

感谢作者:mrseasons

查看原文:go 速学 - 13 - Interface

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1970 次点击  
加入收藏 微博
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传