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 已完结
相关推荐
XMYX-03 小时前
Spring Boot + Prometheus 实现应用监控(基于 Actuator 和 Micrometer)
spring boot·后端·prometheus
@yanyu6664 小时前
springboot实现查询学生
java·spring boot·后端
酷爱码5 小时前
Spring Boot项目中JSON解析库的深度解析与应用实践
spring boot·后端·json
AI小智5 小时前
Google刀刃向内,开源“深度研究Agent”:Gemini 2.5 + LangGraph 打造搜索终结者!
后端
java干货6 小时前
虚拟线程与消息队列:Spring Boot 3.5 中异步架构的演进与选择
spring boot·后端·架构
一只叫煤球的猫6 小时前
MySQL 8.0 SQL优化黑科技,面试官都不一定知道!
后端·sql·mysql
写bug写bug7 小时前
如何正确地对接口进行防御式编程
java·后端·代码规范
不超限7 小时前
Asp.net core 使用EntityFrame Work
后端·asp.net
豌豆花下猫7 小时前
Python 潮流周刊#105:Dify突破10万星、2025全栈开发的最佳实践
后端·python·ai