当前位置: 首页 > ds >正文

GO语言学习(二)

GO语言学习(二)

method(方法)

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

下面给一个具体的事例:

package mainimport ("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方法中有一些要注意的点,我在这里为大家列出一下:

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

自定义类型

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

type ages inttype money float32type months map[string]intm := months {"January":31,"February":28,..."December":31,
}

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

package mainimport "fmt"const(WHITE = iotaBLACKBLUEREDYELLOW
)type Color bytetype Box struct {width, height, depth float64color Color
}type BoxList []Box //a slice of boxesfunc (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.00k := Color(WHITE)for _, b := range bl {if bv := b.Volume(); bv > v {v = bvk = 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。

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

package mainimport "fmt"type Human struct {name stringage intphone 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,重写了匿名字段的方法。

参考代码如下:

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

http://www.xdnf.cn/news/7032.html

相关文章:

  • CSS 浮动与定位以及定位中z-index的堆叠问题
  • 设计练习 - Movie Review Aggregator System
  • 探秘Transformer系列之(33)--- DeepSeek MTP
  • 【爬虫】DrissionPage-6
  • MapReduce 原理深度剖析:从任务执行到参数配置
  • AI编码代理的崛起 - AlphaEvolve与Codex的对比分析引言
  • 61. 旋转链表
  • 理解 plank 自动生成的 copyWithBlock: 方法
  • C++(初阶)(十八)——AVL树
  • 深入解析:如何基于开源OpENer开发EtherNet/IP从站服务
  • 深入浅出IIC协议 - 从总线原理到FPGA实战开发 -- 第一篇:I2C总线协议深度解剖
  • 广和通L610模块通过AT指令访问服务器方案:嵌赛使用
  • 蓝桥杯-不完整的算式
  • select语句的书写顺序
  • DAY 23 训练
  • Vue框架
  • windows 10 做服务器 其他电脑无法访问,怎么回事?
  • 深度学习模型入门:从基础到前沿
  • leetcode 239. 滑动窗口最大值
  • MySQL初阶:sql事务和索引
  • 电子电路:什么是高频电路以及都有哪些应用?
  • 手机打电话时由对方DTMF响应切换多级IVR语音应答(二)
  • UDP的单播组播与广播
  • 使用 Python 打造一个强大的文件系统结构创建器
  • 前脚收购 Windsurf 后,OpenAI 深夜发布 Codex。
  • 基于Yolov8+PyQT的老人摔倒识别系统源码
  • 计算机视觉与深度学习 | Python实现EMD-CNN-LSTM时间序列预测(完整源码、数据、公式)
  • 基于CentOS7制作OpenSSL 1.1的RPM包
  • Webpack DefinePlugin插件介绍(允许在编译时创建JS全局常量,常量可以在源代码中直接使用)JS环境变量
  • HarmonyOS:重构万物互联时代的操作系统范式