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

文章目录

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

结构体

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

//文件名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,得到

>go run struct.go

{GoLearning microCold 200 250000}
{Go microCold 0 0}

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

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

运行后返回1250。

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

接口

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

//文件名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实现相应的成员函数

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 已完结
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

微小冷

请我喝杯咖啡

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值