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 已完结
相关推荐
微尘86 分钟前
C语言存储类型 auto,register,static,extern
服务器·c语言·开发语言·c++·后端
计算机学姐13 分钟前
基于PHP的电脑线上销售系统
开发语言·vscode·后端·mysql·编辑器·php·phpstorm
Freak嵌入式1 小时前
全网最适合入门的面向对象编程教程:50 Python函数方法与接口-接口和抽象基类
java·开发语言·数据结构·python·接口·抽象基类
码拉松1 小时前
千万不要错过,优惠券设计与思考初探
后端·面试·架构
白总Server2 小时前
MongoDB解说
开发语言·数据库·后端·mongodb·golang·rust·php
计算机学姐2 小时前
基于python+django+vue的家居全屋定制系统
开发语言·vue.js·后端·python·django·numpy·web3.py
程序员-珍3 小时前
SpringBoot v2.6.13 整合 swagger
java·spring boot·后端
海里真的有鱼3 小时前
好文推荐-架构
后端
骆晨学长3 小时前
基于springboot的智慧社区微信小程序
java·数据库·spring boot·后端·微信小程序·小程序
AskHarries3 小时前
利用反射实现动态代理
java·后端·reflect