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语言使用大小写来识别是公有还是私有,方法是非常重要的概念需要大家着重掌握,不会的可以在评论区私我,这一节就先讲到这里,在这里助友友们周末快乐。

相关推荐
花酒锄作田7 天前
Gin 框架中的规范响应格式设计与实现
golang·gin
西岸行者7 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习
悠哉悠哉愿意7 天前
【单片机学习笔记】串口、超声波、NE555的同时使用
笔记·单片机·学习
别催小唐敲代码7 天前
嵌入式学习路线
学习
毛小茛7 天前
计算机系统概论——校验码
学习
babe小鑫7 天前
大专经济信息管理专业学习数据分析的必要性
学习·数据挖掘·数据分析
winfreedoms7 天前
ROS2知识大白话
笔记·学习·ros2
在这habit之下7 天前
Linux Virtual Server(LVS)学习总结
linux·学习·lvs
我想我不够好。7 天前
2026.2.25监控学习
学习
im_AMBER7 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode