GO语言学习(二)

GO语言学习(二)

method(方法)

这一节我们介绍一下GO语言的面向对象,之前我们学习了struct结构体,现在我们来解释一下方法method主要是为了简化代码,在计算同类时,使用函数接收方法可以极大的简化代码量。简单来说就是使用receiver来作为method的主体。

下面给一个具体的事例:

go 复制代码
package main

import (
	"fmt"
	"math"
)

type Rectangle struct {
	width, height float64
}

type Circle struct {
	radius float64
}

func (r Rectangle) area() float64 {
	return r.width*r.height
}

func (c Circle) area() float64 {
	return c.radius * c.radius * math.Pi
}

// Rectangle存在字段 height 和 width, 同时存在方法area(), 这些字段和方法都属于Rectangle。
func main() {
	r1 := Rectangle{12, 2}
	r2 := Rectangle{9, 4}
	c1 := Circle{10}
	c2 := Circle{25}

	fmt.Println("Area of r1 is: ", r1.area())
	fmt.Println("Area of r2 is: ", r2.area())
	fmt.Println("Area of c1 is: ", c1.area())
	fmt.Println("Area of c2 is: ", c2.area())
}

在method方法中有一些要注意的点,我在这里为大家列出一下:

go 复制代码
1.虽然method的名字一模一样,但是如果接收者不一样,那么method就不一样(接受者意为接受主体)
2.method里面可以访问接收者的字段
3.调用method通过`.`访问,就像struct里面访问字段一样

自定义类型

自定义类型是一个基于人为自己设定的类型,struct相当于特定的自定义类型,基本结构为type typeName typeLiteral,从中可以看出实际上只是一个定义了一个别名,有点类似于c中的typedef,下面给一个具体的事例。

go 复制代码
type ages int

type money float32

type months map[string]int

m := months {
	"January":31,
	"February":28,
	...
	"December":31,
}

下面我们来给给具体的例子,方便后面的讲解。

go 复制代码
package main

import "fmt"

const(
	WHITE = iota
	BLACK
	BLUE
	RED
	YELLOW
)

type Color byte

type Box struct {
	width, height, depth float64
	color Color
}

type BoxList []Box //a slice of boxes

func (b Box) Volume() float64 {
	return b.width * b.height * b.depth
}

func (b *Box) SetColor(c Color) {
	b.color = c
}

func (bl BoxList) BiggestColor() Color {
	v := 0.00
	k := Color(WHITE)
	for _, b := range bl {
		if bv := b.Volume(); bv > v {
			v = bv
			k = b.color
		}
	}
	return k
}

func (bl BoxList) PaintItBlack() {
	for i := range bl {
		bl[i].SetColor(BLACK)
	}
}

func (c Color) String() string {
	strings := []string {"WHITE", "BLACK", "BLUE", "RED", "YELLOW"}
	return strings[c]
}

func main() {
	boxes := BoxList {
		Box{4, 4, 4, RED},
		Box{10, 10, 1, YELLOW},
		Box{1, 1, 20, BLACK},
		Box{10, 10, 1, BLUE},
		Box{10, 30, 1, WHITE},
		Box{20, 20, 20, YELLOW},
	}

	fmt.Printf("We have %d boxes in our set\n", len(boxes))
	fmt.Println("The volume of the first one is", boxes[0].Volume(), "cm³")
	fmt.Println("The color of the last one is",boxes[len(boxes)-1].color.String())
	fmt.Println("The biggest one is", boxes.BiggestColor().String())

	fmt.Println("Let's paint them all black")
	boxes.PaintItBlack()
	fmt.Println("The color of the second one is", boxes[1].color.String())

	fmt.Println("Obviously, now, the biggest one is", boxes.BiggestColor().String())
}

我们来解释一下这段代码,从自定义类型和接收者定义方法来解释:

  • Color作为byte的别名

  • 定义了一个struct:Box,含有三个长宽高字段和一个颜色属性

  • 定义了一个slice:BoxList,含有Box

  • Volume()定义了接收者为Box,返回Box的容量

  • SetColor(c Color),把Box的颜色改为c

  • BiggestColor()定在在BoxList上面,返回list里面容量最大的颜色

  • PaintItBlack()把BoxList里面所有Box的颜色全部变成黑色

  • String()定义在Color上面,返回Color的具体颜色(字符串格式)

指针为接收者

我们前面传的接受者其实是一个copy的副本,改变这个副本的值是不会影响真实的值,这点偏向于实际的构造问题,故我们不能在这改变真实的值,因此引入了指针来改变实际的值。

这里你也许会问了那SetColor函数里面应该这样定义*b.Color=c,而不是b.Color=c,因为我们需要读取到指针相应的值,其实Go里面这两种方式都是正确的,当你用指针去访问相应的字段时(虽然指针没有任何的字段),Go知道你要通过指针去获取这个值,看到了吧,Go的设计是不是越来越吸引你了。

所以在实际开发中你不用担心你是调用的指针的method还是不是指针的method。

方法继承

首先可以使用匿名字段来实现继承,在这里面中匿名字段实现了一个method,那么包含这个匿名字段的struct也能调用该method。

让我们来看下面这个例子:

go 复制代码
package main

import "fmt"

type Human struct {
	name string
	age int
	phone string
}

type Student struct {
	Human //匿名字段
	school string
}

type Employee struct {
	Human //匿名字段
	company string
}

//在human上面定义了一个method
func (h *Human) SayHi() {
	fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
}

func main() {
	mark := Student{Human{"Mark", 25, "222-222-YYYY"}, "MIT"}
	sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"}

	mark.SayHi() // 相当于继承的使用了接收者为*human的方法
	sam.SayHi()
}

方法重写

在使用方法中通过Employee实现SayHi,可以参考匿名字段冲突一样的道理,我们可以在Employee上面定义一个method,重写了匿名字段的方法。

参考代码如下:

go 复制代码
package main

import "fmt"

type Human struct {
	name string
	age int
	phone string
}

type Student struct {
	Human //匿名字段
	school string
}

type Employee struct {
	Human //匿名字段
	company string
}

//Human定义method
func (h *Human) SayHi() {
	fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
}

//Employee的method重写Human的method
func (e *Employee) SayHi() {
	fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name,
		e.company, e.phone) //Yes you can split into 2 lines here.
}

func main() {
	mark := Student{Human{"Mark", 25, "222-222-YYYY"}, "MIT"}
	sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"}

	mark.SayHi()
	sam.SayHi()
}

这个重写方法很像python的重写,相当于写出不同的方法来实现方法的重写。

总结

在GO语言的面向对象编程中没有啥关键字和标识符来标记范围,因此GO语言使用大小写来识别是公有还是私有,方法是非常重要的概念需要大家着重掌握,不会的可以在评论区私我,这一节就先讲到这里,在这里助友友们周末快乐。

相关推荐
向上的车轮3 小时前
MATLAB学习笔记(七):MATLAB建模城市的雨季防洪排污的问题
笔记·学习·matlab
前端小崔4 小时前
从零开始学习three.js(18):一文详解three.js中的着色器Shader
前端·javascript·学习·3d·webgl·数据可视化·着色器
龙湾开发5 小时前
计算机图形学编程(使用OpenGL和C++)(第2版)学习笔记 10.增强表面细节(二)法线贴图
c++·笔记·学习·图形渲染·贴图
liang_20265 小时前
【HT周赛】T3.二维平面 题解(分块:矩形chkmax,求矩形和)
数据结构·笔记·学习·算法·平面·总结
虾球xz5 小时前
游戏引擎学习第290天:完成分离渲染
c++·人工智能·学习·游戏引擎
虾球xz5 小时前
游戏引擎学习第285天:“Traversables 的事务性占用”
c++·学习·游戏引擎
虾球xz6 小时前
游戏引擎学习第280天:精简化的流式实体sim
数据库·c++·学习·游戏引擎
深度学习入门6 小时前
学习深度学习是否要先学习机器学习?
人工智能·深度学习·神经网络·学习·机器学习·ai·深度学习入门
FAREWELL000756 小时前
Unity基础学习(十五)核心系统——音效系统
学习·unity·c#·游戏引擎
岁岁岁平安6 小时前
Vue3学习(组合式API——Watch侦听器、watchEffect()详解)
前端·javascript·vue.js·学习·watch侦听器·组合式api