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 已完结
相关推荐
姑苏洛言1 小时前
编写产品需求文档:黄历日历小程序
前端·javascript·后端
姑苏洛言2 小时前
搭建一款结合传统黄历功能的日历小程序
前端·javascript·后端
你的人类朋友2 小时前
🍃认识一下boomi
后端
苏三说技术2 小时前
MySQL的三大日志
后端
豌豆花下猫2 小时前
让 Python 代码飙升330倍:从入门到精通的四种性能优化实践
后端·python·ai
hackchen2 小时前
Go与JS无缝协作:Goja引擎实战之错误处理最佳实践
开发语言·javascript·golang
南雨北斗3 小时前
TP6使用PHPMailer发送邮件
后端
你的人类朋友3 小时前
🤔什么时候用BFF架构?
前端·javascript·后端
争不过朝夕,又念着往昔4 小时前
Go语言反射机制详解
开发语言·后端·golang
Jerry Lau4 小时前
go go go 出发咯 - go web开发入门系列(二) Gin 框架实战指南
前端·golang·gin