当前位置:网站首页>GO语言-接口
GO语言-接口
2022-06-21 15:32:00 【一边学习一边哭】
概述
接口中只定义方法,没有方法的具体实现。方法的代码需要类型来实现。
如果定义了结构体,去实现接口中的方法。那么这个结构体就是接口的实现。
- 当需要接口类型对象时,可以使用任意实现类对象代替。
- 接口对象不能调用实现类的字段。
接口的作用
- 接口作用就是解耦合。实现在修改一部分代码的时候,其他部分代码受到的影响最小。
- 接口是吧功能定义和功能实现分离开。
- 通过接口,可以模拟面向对象语言的多态。
语法
//1.定义接口
type interface_name interface {
method_name1 [return_type]
method_name2 [return_type]
...
}
//定义结构体
type struct_name1 struct {
字段名称 字段类型
}
//实现接口方法
func (variable struct_name1) method_name1(parameter list) (return list) {
方法实现
}
func (variable struct_name1) method_name2(parameter list) (return list) {
方法实现
}模拟一个USB接口。实现start()和stop()方法。两个不同的结构体实现鼠标和存储(现象对象的多态)。
//接口
type USB interface {
start()
stop()
}
//鼠标结构体
type Mouse struct {
name string
}
//闪存结构体
type FlashDisk struct {
name string
}
//结构体方法
func (m Mouse) start() {
fmt.Println(m.name, "鼠标开始工作...")
}
func (m Mouse) stop() {
fmt.Println(m.name, "鼠标停止工作...")
}
func (f FlashDisk) start() {
fmt.Println(f.name, "闪存已插入,可以开始使用...")
}
func (f FlashDisk) stop() {
fmt.Println(f.name, "闪存已拔出...")
}
//测试方法
func testInterface(usb USB) {
usb.start()
usb.stop()
}
func main() {
mouse1 := Mouse{"雷蛇超级鼠标"}
flashDisk1 := FlashDisk{"15TB超级闪存"}
testInterface(mouse1)
testInterface(flashDisk1)
var usb USB = Mouse{"罗技鼠标"}
usb.start()
usb.stop()
}
空接口
空接口:不包含任何的方法的接口。
所有的类型都实现了空接口,正因如此,空接口类型可以存储任意类型的值。
作用:可以定义空接口类型,定义array、slice、map,类型为空接口类型。就可以存储任意类型的值。
空接口类型存储任意类型值
//接口
type A interface {
}
//结构体
type Animal struct {
name string
}
type People struct {
name string
age int
}
func main() {
var a1 A = Animal{"minacat"}
var a2 A = People{"liqi", 18}
var a3 A = "aaa"
var a4 A = 555
fmt.Printf("a1的值:%v, a1的类型:%T\n", a1, a1)
fmt.Printf("a2的值:%v, a2的类型:%T\n", a2, a2)
fmt.Printf("a3的值:%v, a3的类型:%T\n", a3, a3)
fmt.Printf("a4的值:%v, a4的类型:%T\n", a4, a4)
}
array、slice、map类型定义为空接口
func main() {
//map, key字符串,value任意类型
map1 := make(map[string]interface{})
map1["name"] = "张三"
map1["age"] = 18
map1["friend"] = []string{"李四", "王五"}
fmt.Printf("map值:%v, map类型:%T\n", map1, map1)
//切片,存储任意类型
slice1 := []interface{}{1, "张三", true}
fmt.Printf("切片值:%v, 切片类型:%T\n", slice1, slice1)
//数组,存储任意类型
array1 := [3]interface{}{2, "李四", true}
fmt.Printf("数组值:%v, 数组类型:%T\n", array1, array1)
}
接口嵌套(继承)
接口是多继承的,一个类可以继承多个父类。

如图所示,接口C继承了接口A(test1()方法)和接口B(test2()方法),接口C自己有test3()方法。所以实现接口C时需要同时实现A\B\C三个接口的方法。
可以定义一个结构体,实现A\B\C三个接口的方法。此结构体到底是哪个接口的实现,取决于变量声明时的类型。
//接口A
type A interface {
test1()
}
//接口B
type B interface {
test2()
}
//接口C,继承接口A/B
type C interface {
A
B
test3()
}
//结构体
type Xtest struct {
}
//方法实现
func (x Xtest) test1() {
fmt.Println("test1()方法...")
}
func (x Xtest) test2() {
fmt.Println("test2()方法...")
}
func (x Xtest) test3() {
fmt.Println("test3()方法...")
}
func main() {
var x1 Xtest = Xtest{}
fmt.Println("--接口A的实现--") //只有test1方法,无法调用test2、test3方法
var a1 A = x1
a1.test1()
fmt.Println("--接口B的实现--") //只有test2方法,无法调用test1、test3方法
var b1 B = x1
b1.test2()
fmt.Println("--接口C的实现--") //可以调用test1、test2、test3方法
var c1 C = x1
c1.test1()
c1.test2()
c1.test3()
}接口断言
获取接口所接受的真实类型
语法一:
判断接口对象是不是实际类型,是则布尔参数为true,反之false。
变量参数, 布尔参数 := 接口对象.(实际类型)
语法二:
实现多态的对于不同结构体的处理。
switch 变量参数 := 接口对象.(type) {
case 实际类型1:
...
case 实际类型2:
...
}//接口
type USB interface {
start()
stop()
}
//鼠标结构体
type Mouse struct {
name string
}
//闪存结构体
type FlashDisk struct {
name string
}
//结构体方法
func (m Mouse) start() {
fmt.Println(m.name, "鼠标开始工作...")
}
func (m Mouse) stop() {
fmt.Println(m.name, "鼠标停止工作...")
}
func (f FlashDisk) start() {
fmt.Println(f.name, "闪存已插入,可以开始使用...")
}
func (f FlashDisk) stop() {
fmt.Println(f.name, "闪存已拔出...")
}
//测试方法
func testInterface(usb USB) {
switch instaceType := usb.(type) {
case Mouse:
fmt.Println("您接入了鼠标,正在检查初始化驱动程序...")
instaceType.start()
instaceType.stop()
case FlashDisk:
fmt.Println("您接入存储,正在扫描磁盘...")
instaceType.start()
fmt.Println("您可以随时拔出存储...")
instaceType.stop()
}
}
func main() {
mouse1 := Mouse{"雷蛇超级鼠标"}
flashDisk1 := FlashDisk{"15TB超级闪存"}
testInterface(mouse1)
fmt.Println("------------------")
testInterface(flashDisk1)
}

边栏推荐
- Counter attack of flour dregs: MySQL 66 questions, 20000 words + 50 pictures!
- What is a naked cat
- Phantom star VR product details 31: escape from the secret room
- Live long to see the true chapter
- Program for counting black and white pixel values in pictures
- Phy336 Computational Physics
- Three sides of the headline: tostring(), string Valueof, (string) forced rotation. What is the difference
- 2022 latest MySQL interview questions
- Small case of anti shake function
- Summary of statistical learning methods
猜你喜欢

Browser evaluation: a free, simple and magical super browser - xiangtian browser
![[Yugong series] February 2022 wechat applet -app Debug JSON configuration attribute](/img/33/103a207dc085c431557981b3c9a1d5.jpg)
[Yugong series] February 2022 wechat applet -app Debug JSON configuration attribute

Redis introduction and Practice (with source code)

Not only products, FAW Toyota can give you "all-round" peace of mind

First Canary deployment with rancher

Idea restart
![[North Asia data recovery] SQLSERVER database encrypted data recovery case sharing](/img/6d/7fc3c563fa1c503cbf09f345a4c042.jpg)
[North Asia data recovery] SQLSERVER database encrypted data recovery case sharing

Retrieve the compressed package password

Use Matplotlib to draw the first figure

soEasyCheckin
随机推荐
我不太想在网上开户,网上股票开户安全吗
Office operation sorting notes
Judge password strength - Optimization
进程之间使用共享内存通信
Fundamentals of C language 13: file input / output
马拦过河卒
Analysis of China's social financing scale and financing structure in 2021: RMB loans to the real economy account for more than 60%[figure]
Kubeneters installation problems Collection
Use OpenCV to decompose the video into single frame pictures and synthesize the video with pictures
Non local network: early human attempts to tame transformer in CV | CVPR 2018
Jason Basics
Numpy: basic package for high performance scientific computing & data analysis
In 2021, China's deposit balance continued to grow, and the balance of RMB and foreign currency deposits reached a record high [figure]
What is PDT
Work assessment of contract law of Jilin University in March of the 22nd spring -00100
Merge two ordered linked lists
Integration of sparkstreaming and sparksql
Connecting MySQL with C language under Windows system
Phantom star VR product details 32: Infinite War
理财产品预约赎回确认日是什么?