赞
踩
视频来源:B站《golang入门到项目实战 [2022最新Go语言教程,没有废话,纯干货!]》
文章为自己整理的学习笔记,侵权即删,谢谢支持!
go语言的接口,是一种新的类型定义,它把所有的具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了这个接口。
语法格式和方法非常类似。
/* 定义接口 */ type interface_name interface { method_name1 [return_type] method_name2 [return_type] method_name3 [return_type] ... method_namen [return_type] } /* 定义结构体 */ type struct_name struct { /* variables */ } /* 实现接口方法 */ func (struct_name_variable struct_name) method_name() [return_type] { /* 方法实现 */ } ... /* 实现接口方法 */ func (struct_name_variable struct_name) method_name() [return_type] { /* 方法实现 */ }
在接口定义中定义,若干个空方法。这些方法都具有通用性。
定义一个USB接口,有读read和写write两个方法,再定义一个电脑Computer和一个手机Mobile来实现这个接口。
定义USB接口:
type USB interface {
read()
write()
}
定义Computer结构体:
type Computer struct {
}
定义Mobile结构体:
type Mobile struct {
}
Computer实现USB接口方法:
func (c Computer) read() {
fmt.Println("computer read...")
}
func (c Computer) write() {
fmt.Println("computer write...")
}
Mobile实现USB接口方法:
func (c Mobile) read() {
fmt.Println("mobile read...")
}
func (c Mobile) write() {
fmt.Println("mobile write...")
}
测试:
package main import "fmt" type USB interface { read() write() } type Computer struct { } type Mobile struct { } func (c Computer) read() { fmt.Println("computer read...") } func (c Computer) write() { fmt.Println("computer write...") } func (c Mobile) read() { fmt.Println("mobile read...") } func (c Mobile) write() { fmt.Println("mobile write...") } func main() { c := Computer{ } m := Mobile{ } c.read() c.write() m.read() m.write() }
运行结果:
computer read...
computer write...
mobile read...
mobile write...
接口本身不能创建实例,但是可以指向一个实现了该接口的自定义类型的变量(实例)
接口中所有的方法都没有方法体,即都是没有实现的方法
在 Golang 中,一个自定义类型需要将某个接口的所有方法都实现,我们说这个自定义类型实现了该接口
一个自定义类型只有实现了某个接口,才能将该自定义类型的实例(变量)赋给接口类型
只要是自定义数据类型,就可以实现接口,不仅仅是结构体类型。
一个自定义类型可以实现多个接口
Golang 接口中不能有任何变量
实现接口必须实现接口中的所有方法
下面我们定义一个OpenClose接口,里面有两个方法open和close,定义个Door结构体,实现其中一个方法。
package main import "fmt" type OpenClose interface { open() close() } type Door struct { } func (d Door) open() { fmt.Println("open door...") } func main() { var oc OpenClose oc = Door{ <
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。