4

#yyds干货盘点#【愚公系列】2022年09月 Go教学课程 034-接口和多态

 2 years ago
source link: https://blog.51cto.com/u_15437432/5660031
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

1.接口的定义

在生日常活中无时不刻不在使用各种接口,比如电脑的usb,手机的充电接口等等。

在计算机程序中接口就是一种规范与标准,只是规定了要做哪些事情,具体怎么做,接口是不管的,接口把所有的具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了这个接口,接口是一种抽象类型,它并没有暴露所含数据的布局或者内部结构,当然也没有那些数据的基本操作,它所提供的仅仅是一些方法而已。

很多面向对象的编程语言都有接口的概念,Go语言的接口的独特之处在于它是隐式实现的。换句话说,对于一个具体的类型,无需声明它实现了哪些接口,只要提供接口所必需的方法即可。

2.接口的基本使用

package main

import "fmt"

type Personer interface {
	SayHello()
	//Say()
}
type Student struct {
}

func (s *Student) SayHello() {
	fmt.Println("老师好")
}

type Teacher struct {
}

func (t *Teacher) SayHello() {
	fmt.Println("学生好")
}

func main() {
	// 对象名.方法名
	var stu Student
	//stu.SayHello()
	var teacher Teacher
	//teacher.SayHello()
	// 通过接口变量来调用,必须都实现接口中所声明的方法。

	var person Personer
	person = &stu
	person.SayHello() // 调用的是Student 实现的SayHello方法
	person = &teacher
	person.SayHello()

}

在上面的例子中,我们定义了一个接口Personer ,接口里面有一个方法SayHello()。然后我们在main函数里面定义了一个Student 类型变量,并分别为之赋值为Student 和Personer 。然后调用SayHello()方法,输出结果如下:

#yyds干货盘点#【愚公系列】2022年09月 Go教学课程 034-接口和多态_移动硬盘

3.多态的实现

package main

import "fmt"

type Personer interface {
	SayHello()
}
type Student struct {
}

func (s *Student) SayHello() {
	fmt.Println("老师好")
}

type Teacher struct {
}

func (t *Teacher) SayHello() {
	fmt.Println("学生好")
}

// 多态。

func WhoSayHi(h Personer) {
	h.SayHello()
}

func main() {
	var stu Student
	var teacher Teacher
	WhoSayHi(&stu)
	WhoSayHi(&teacher)
}

#yyds干货盘点#【愚公系列】2022年09月 Go教学课程 034-接口和多态_移动硬盘_02
package main

import "fmt"

type Stroager interface {
	Read()
	Writer()
}

// 移动硬盘
type MDisk struct {
}

func (m *MDisk) Read() {
	fmt.Println("移动硬盘读取数据")
}
func (m *MDisk) Writer() {
	fmt.Println("移动硬盘写入数据")
}

// U盘
type UDisk struct {
}

func (u *UDisk) Read() {
	fmt.Println("U盘读取数据")
}
func (u *UDisk) Writer() {
	fmt.Println("U盘写入数据")
}

// 定义一个函数
func Computer(c Stroager) {
	c.Read()
	c.Writer()
}
func main() {
	var udisk UDisk
	var mdisk MDisk
	Computer(&udisk)
	Computer(&mdisk)
}

#yyds干货盘点#【愚公系列】2022年09月 Go教学课程 034-接口和多态_数据_03

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK