接口(interface)

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,接口类型为指针
沪ICP备17055033号-2