go语言教程6:结构体、接口以及面向对象

文章目录

go语言教程:安装入门➡️for循环➡️数组、切片和指针➡️switch和map➡️函数进阶

结构体

在Go语言中结构体用type ... struct标识,下面做一个最简单的示例

go 复制代码
//文件名struct.go
package main
import "fmt"

type Note struct{
	title string
	author string
	pages int
	words int
}

func main(){
	fmt.Println(Note{"GoLearning", "microCold", 200, 250000})

	var n Note
	n.title = "Go"
	n.author = "microCold"
	fmt.Println(n)

}

其中,Notes是一个结构体,里面有4个成员变量,分别是title, author, pages, words,表示笔记的标题、作者、页数和字数。

在命令行中调用go run test.go,得到

golang 复制代码
>go run struct.go
{GoLearning microCold 200 250000}
{Go microCold 0 0}

Go语言结构体的成员函数需要在结构体外面定义,比如希望定义一个函数,求平均每页笔记的字数,那么可以写成如下形式

go 复制代码
func (n Note) GetWordsPP() int {
    return n.words / n.pages
}
func main(){
	n := Note{"GoLearning", "microCold", 200, 250000}
	fmt.Println(n.GetWordsPP())
}

运行后返回1250。

由此可见,结构体的成员方法和普通函数在定义上的区别就是,会在函数名的前面添加一个括号,里面是结构体变量。

接口

结构体中只有成员变量,成员方法则需要额外定义。而接口,则将一些常用的成员方法定义在一起,而任何结构体,只要实现了接口中的方法,便算是对这个接口的一种继承。

go 复制代码
//文件名interface.go
package main
import "fmt"

type Book interface{
	GetWordsPP() int
}

type Note struct{
	title string
	author string
	pages int
	words int
}

func (n Note) GetWordsPP() int {
    return n.words / n.pages
}

type Noval struct{
	title string
	author string
	finished bool
	pages int
	words int
}

func (n Noval) GetWordsPP() int {
    return n.words / n.pages
}

func main(){
	var b Book
	b = Note{"GoLearning", "microCold", 200, 250000}
	fmt.Println(b.GetWordsPP())

	b = Noval{"Nahan", "Luxun", true, 200, 250000}
	fmt.Println(b.GetWordsPP())
}

尽管上面的代码中,没有任何直接的证据表明Note或者Noval是Book的子类,但由于二者均实现了接口中的方法GetWordsPP,从而跻身Book行列,所以main函数中声明了一个Book型变量b,然后就可以为其示例化为Note或者Noval类。

多态

面向对象三大要素,封装、继承、多态,这三点go语言几乎都不能十分满足。但好歹结构体可以把成员变量和函数归拢到一起,包的调用进一步加强了对变量的保护,算是完成了封装。

而对接口的隐式调用,则相当于完成了继承。

在Go语言中,多态可以简单地理解为多继承,下面新定义一个接口,并针对Book和Note实现相应的成员函数

go 复制代码
type Info interface{
	GetInfo()
}

func (n Note) GetInfo(){
    fmt.Println(n.title, "的作者是", n.author)
}

func (n Noval) GetInfo() {
	var f string
	if n.finished {
		f = "已完结"
	}else{
		f = "未完结"
	}
    fmt.Println(n.title, "的作者是", n.author, f)
}

func main(){
	b := Note{"GoLearning", "microCold", 200, 250000}
	b.GetInfo()

	n = Noval{"Nahan", "Luxun", true, 200, 250000}
	n.GetInfo()
}

运行结果如下

复制代码
GoLearning 的作者是 microCold
Nahan 的作者是 Luxun 已完结
相关推荐
yumuing25 分钟前
融合动态权重与抗刷机制的网文评分系统——基于优书网、IMDB与Reddit的混合算法实践
后端·算法·架构
cyz14100144 分钟前
树莓派4B配置wifi热点,可访问http协议
linux·网络·windows·后端·网络协议·http·树莓派
橘子青衫1 小时前
并发编程难题:死锁、活锁、饥饿深度剖析
java·后端
顾琬清1 小时前
Linux系统Docker部署开源在线协作笔记Trilium Notes与远程访问详细教程
开发语言·后端·golang
李白的粉1 小时前
基于springboot的个人博客系统
java·spring boot·后端·毕业设计·课程设计·源代码·个人博客系统
Charlie__ZS1 小时前
Spring其它知识点
java·后端·spring
Aska_Lv1 小时前
mysql---主从延时问题
后端
细心的莽夫2 小时前
Docker学习笔记
运维·笔记·后端·学习·docker·容器
省长2 小时前
Sa-Token v1.42.0 发布 🚀,新增 API Key、TOTP 验证码、RefreshToken 反查等能力
java·后端·开源
小蒜学长2 小时前
机动车号牌管理系统设计与实现(代码+数据库+LW)
开发语言·数据库·spring boot·后端·spring·oracle