go 速学 - 13 - Interface

目录

摘要

定义接口,实现接口,使用接口,作为参数的接口,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,接口类型为指针
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值