Go语言中的Oop面向对象
Go In OOp
- 一、 Go是面向对象的吗?
- 二、Structs Instead of Classes 结构体 - OOP in Go
- 三、 Composition Instead of Inheritance 组合嵌套 - OOP in Go
- 1.Composition by embedding structs
- 2. Embedding slice of structs
- 四、Polymorphism 多态 - OOP in Go
- 1. Polymorphism using an interface
- 2. Adding a new income stream to the above program
一、 Go是面向对象的吗?
Go is not a pure object oriented programming language. This excerpt taken from Go's FAQs answers the question of whether Go is Object Oriented.
Yes and no. Although Go has types and methods and allows an object-oriented style of programming, there is no type hierarchy. The concept of “interface” in Go provides a different approach that we believe is easy to use and in some ways more general. There are also ways to embed types in other types to provide something analogous—but not identical—to subclassing. Moreover, methods in Go are more general than in C++ or Java: they can be defined for any sort of data, even built-in types such as plain, “unboxed” integers. They are not restricted to structs (classes)
In the upcoming tutorials, we will discuss how object oriented programming concepts can be implemented using Go. Some of them are quite different in implementation compared to other object oriented languages such as Java
.
Go不是一种纯粹的面向对象编程语言。这段摘自Go的faq,回答了Go是否是面向对象的问题。
是也不是。虽然Go有类型和方法,并且允许面向对象的编程风格,但是没有类型层次结构。Go中的“接口”概念提供了一种不同的方法,我们认为这种方法易于使用,并且在某些方面更通用。还有一些方法可以将类型嵌入到其他类型中,以提供类似于子类化(但不完全相同)的东西。此外,Go中的方法比c++或Java中的方法更通用:可以为任何类型的数据定义方法,甚至可以为内置类型(如普通的“未装箱”整数)定义方法。它们并不局限于结构体(类)。
在接下来的教程中,我们将讨论如何使用Go实现面向对象编程概念。它们中的一些在实现上与其他面向对象语言(如Java)有很大的不同。
二、Structs Instead of Classes 结构体 - OOP in Go
// 目录结构│ └── oop│ ├── employee│ │ └── employee.go│ ├── go.mod│ └── main.go// main.gopackage mainimport ("oop/employee")func main() {e := employee.Employee{FirstName: "Mei", LastName: "Jin", TotalLeaves: 666, LeavesTaken: 555}e.LeavesRemaining()var c employee.Employeec.LeavesRemaining()d := employee.New("Liang", "xiaoxiao", 888, 777)d.LeavesRemaining()}// employee.gopackage employeeimport "fmt"type Employee struct {FirstName stringLastName stringTotalLeaves intLeavesTaken int}func New(firstName string, lastName string, totalLeave int, leavesTaken int) Employee {e := Employee{firstName, lastName, totalLeave, leavesTaken}return e}func (e Employee) LeavesRemaining() {fmt.Printf("%s %s has %d leaves remaining\n", e.FirstName, e.LastName, (e.TotalLeaves - e.LeavesTaken))}// 运行结果// Mei Jin has 111 leaves remaining// has 0 leaves remaining// Liang xiaoxiao has 111 leaves remaining
三、 Composition Instead of Inheritance 组合嵌套 - OOP in Go
1.Composition by embedding structs
package mainimport ( "fmt")type author struct { firstName stringlastName stringbio string}func (a author) fullName() string { return fmt.Sprintf("%s %s", a.firstName, a.lastName)}type blogPost struct { title stringcontent stringauthor}func (b blogPost) details() { fmt.Println("Title: ", b.title)fmt.Println("Content: ", b.content)fmt.Println("Author: ", b.fullName())fmt.Println("Bio: ", b.bio)}func main() { author1 := author{"MeiJin","Liang","Golang Enthusiast",}blogPost1 := blogPost{"Inheritance in Go","Go supports composition instead of inheritance",author1,}blogPost1.details()}// Title: Inheritance in GO// Content: GO supports composition instead of inheritance// Author: MeiJin Liang// Bio: Golang Enthusiast
2. Embedding slice of structs
package mainimport "fmt"type Author struct {firstName stringlastName stringbio string}func (a Author) fullName() string {return fmt.Sprintf("%s %s", a.firstName, a.lastName)}type BlogPost struct {title stringcontent stringAuthor}func (p BlogPost) details() {fmt.Println("Title:", p.title)fmt.Println("Content:", p.content)fmt.Println("Author:", p.fullName()) // 注意调用的是blogpost里author的fillName方法fmt.Println("Bio:", p.bio)}type WebSite struct {BlogPosts []BlogPost}func (w WebSite) contents() {fmt.Println("Contents of Website\n")for _, v := range w.BlogPosts {v.details()fmt.Println()}}func main() {author := Author{"MeiJin","Liang","Golang Enthusiast",}blogpost1 := BlogPost{"Inheritance in GO","GO supports composition instead of inheritance",author,}blogPost2 := BlogPost{"Struct instead of Classes in Go","Go does not support classes but methods can be added to structs",author,}blogPost3 := BlogPost{"Concurrency","Go is a concurrent language and not a parallel one",author,}w := WebSite{BlogPosts: []BlogPost{blogpost1, blogPost2, blogPost3},}w.contents()}// Contents of Website// Title: Inheritance in GO// Content: GO supports composition instead of inheritance// Author: MeiJin Liang// Bio: Golang Enthusiast// Title: Struct instead of Classes in Go// Content: Go does not support classes but methods can be added to structs// Author: MeiJin Liang// Bio: Golang Enthusiast// Title: Concurrency// Content: Go is a concurrent language and not a parallel one// Author: MeiJin Liang// Bio: Golang Enthusiast
四、Polymorphism 多态 - OOP in Go
1. Polymorphism using an interface
package mainimport "fmt"type Income interface {calculate() intsource() string}type FixedBilling struct {projectName stringbiddedAmount int}type TimeAndMaterial struct {projectName stringnoOfHours inthourlyRate int}func (fb FixedBilling) calculate() int {return fb.biddedAmount}func (fb FixedBilling) source() string {return fb.projectName}func (tm TimeAndMaterial) calculate() int {return tm.noOfHours * tm.hourlyRate}func (tm TimeAndMaterial) source() string {return tm.projectName}func calculateNetIncome(ic []Income) { // 设置一个变量 每次循环更新一次 最后为结果var netincome int = 0for _, income := range ic {fmt.Printf("Income From %s = $%d\n", income.source(), income.calculate())netincome += income.calculate()}fmt.Printf("Net income of organization = $%d", netincome)}func main() {project1 := FixedBilling{projectName: "Project 1", biddedAmount: 5000}project2 := FixedBilling{projectName: "Project 2", biddedAmount: 10000}project3 := TimeAndMaterial{projectName: "Project 3", noOfHours: 160, hourlyRate: 25}incomeStreams := []Income{project1, project2, project3}calculateNetIncome(incomeStreams)}// Income From Project 1 = $5000// Income From Project 2 = $10000// Income From Project 3 = $4000// Net income of organization = $19000
2. Adding a new income stream to the above program
package mainimport "fmt"type Income interface {calculate() intsource() string}type FixedBilling struct {projectName stringbiddedAmount int}type TimeAndMaterial struct {projectName stringnoOfHours inthourlyRate int}type Advertisement struct {adName stringCPC intnoOfClicks int}func (fb FixedBilling) calculate() int {return fb.biddedAmount}func (fb FixedBilling) source() string {return fb.projectName}func (tm TimeAndMaterial) calculate() int {return tm.noOfHours * tm.hourlyRate}func (tm TimeAndMaterial) source() string {return tm.projectName}func (a Advertisement) calculate() int {return a.CPC * a.noOfClicks}func (a Advertisement) source() string {return a.adName}func calculateNetIncome(ic []Income) {var netincome int = 0for _, income := range ic {fmt.Printf("Income From %s = $%d\n", income.source(), income.calculate())netincome += income.calculate()}fmt.Printf("Net income of organization = $%d", netincome)}func main() {project1 := FixedBilling{projectName: "Project 1", biddedAmount: 5000}project2 := FixedBilling{projectName: "Project 2", biddedAmount: 10000}project3 := TimeAndMaterial{projectName: "Project 3", noOfHours: 160, hourlyRate: 25}bannerAd := Advertisement{adName: "Banner Ad", CPC: 2, noOfClicks: 500}popupAd := Advertisement{adName: "Popup Ad", CPC: 5, noOfClicks: 750}incomeStreams := []Income{project1, project2, project3, bannerAd, popupAd}calculateNetIncome(incomeStreams)}// Income From Project 1 = $5000// Income From Project 2 = $10000// Income From Project 3 = $4000// Income From Banner Ad = $1000// Income From Popup Ad = $3750// Net income of organization = $23750
技术小白记录学习过程,有错误或不解的地方请指出,如果这篇文章对你有所帮助请点点赞收藏+关注谢谢支持 !!!
相关文章:
Go语言中的Oop面向对象
Go In OOp 一、 Go是面向对象的吗?二、Structs Instead of Classes 结构体 - OOP in Go三、 Composition Instead of Inheritance 组合嵌套 - OOP in Go1.Composition by embedding structs2. Embedding slice of structs 四、Polymorphism 多态 - OOP in Go1. Polymorphism u…...
Duplicate keys detected: ‘1‘. This may cause an update error.
报错 Duplicate keys detected: ‘1’. This may cause an update error. 注释: 检测到重复密钥:‘1’。这可能会导致更新错误。 解决 首先判断是因为for循环导致的,检查是否出现重复。 笔者是同一个页面两处for循环导致...

C++(8.21)c++初步
1.斐波那契: #include <iostream> #include<iomanip>using namespace std;int main() {cout << "Hello World!" << endl;int a[10];for(int i0;i<10;i){if(0i||1i){a[i]1;}elsea[i]a[i-1]a[i-2];cout <<setw(4) <&l…...

【【Verilog典型电路设计之log函数的Verilog HDL设计】】
Verilog典型电路设计之log函数的Verilog HDL设计 log函数是一种典型的单目计算函数,与其相应的还有指数函数、三角函数等。对于单目计算函数的硬件加速器设计一般两种简单方法:一种是查找表的方式;一种是使用泰勒级数展开成多项式进行近似计算。这两种方式在设计方…...
数字放大(C++)
系列文章目录 1.进阶的卡沙_睡觉觉觉得的博客-CSDN博客 2. 数1的个数_睡觉觉觉得的博客-CSDN博客 3. 双精度浮点数的输入输出_睡觉觉觉得的博客-CSDN博客 4. 足球联赛积分_睡觉觉觉得的博客-CSDN博客 5. 大减价(一级)_睡觉觉觉得的博客-CSDN博客 6. 小写字母的判断_睡觉觉觉得…...

FOC控制框架图
pmsm电机数学模型以及FOC控制框图(开源小项目FOC控制BLDC电机)_foc 框图_栋哥爱做饭的博客-CSDN博客 电机控制----FOC框架讲解_foc电机控制_修才生的博客-CSDN博客...
Spring工具类(获取bean,发布事件)
spring-beans-5.3.1.jar Component public final class SpringUtils implements BeanFactoryPostProcessor{/*** Spring应用上下文环境*/private static ConfigurableListableBeanFactory beanFactory;//初始化成员变量Overridepublic void postProcessBeanFactory(Configurab…...

腾讯云和阿里云服务器折扣对比_看看哪家划算?
阿里云服务器和腾讯云服务器根据购买时长可以享受一定的优惠折扣,综合对比下来腾讯云折扣更低,阿腾云来对比下阿里云和腾讯云的云服务器根据购买时长可以享受的常规折扣对比: 目录 阿里云和腾讯云折扣对比 阿里云服务器常规折扣 腾讯云服…...
GO语言中的Defer与Error异常报错详细教程
目录标题 一、Defer1. Example2. Deferred methods 延迟方法3. Arguments evaluation 延迟参数4. Stack of defers 延迟程序堆栈5. Practical use of defer 实际使用 二、Error1. Example2. PathError3. DNSError4. Direct Comparison 直接比较5. Do not ignore errors 不要忽略…...

AP6315 DC单节锂电池充电IC 同步2A锂电芯片
概述 是一款面向5V交流适配器的2A锂离子电池充电器。它是采用1.5MHz固定频率的同步降压型转换器,因此具有高达90%以上的充电效率,自身发热量极小。包括完整的充电终止电路、自动再充电和一个达1%的4.2V预设充电电压,内部集成了防反灌保护、输…...

PDF校对工具正式上线,为用户提供卓越的文档校对解决方案
为满足当下对数字化文档校对的精准需求,我们今日正式发布全新的PDF校对工具。经过深入的技术研发与细致的测试,该工具旨在为企业和个人用户带来一个高效且准确的PDF文档校对平台。 PDF校对工具的主要特性: 1.全面性校对:工具支持…...
WSL 配置 Oracle 19c 客户端
Windows WSL 登陆后显示如下: Welcome to Ubuntu 20.04.4 LTS (GNU/Linux 4.4.0-19041-Microsoft x86_64)* Documentation: https://help.ubuntu.com* Management: https://landscape.canonical.com* Support: https://ubuntu.com/advantageSystem information as…...

ChatGPT⼊门到精通(1):ChatGPT 是什么
⼀、直观感受 1、公司 OpenAI(美国) 2、官⽅⽹站 3、登录ChatGPT  at com.alibaba.druid.pool…...
软考高级系统架构设计师系列论文八十九:论软件需求分析方法和工具的选用
软考高级系统架构设计师系列论文八十九:论软件需求分析方法和工具的选用 一、软件需求相关知识点二、摘要三、正文四、总结一、软件需求相关知识点 软考高级系统架构设计师:论软件需求管理...

java八股文面试[JVM]——类加载器
一、类加载器的概念 类加载器是Java虚拟机用于加载类文件的一种机制。在Java中,每个类都由类加载器加载,并在运行时被创建为一个Class对象。类加载器负责从文件系统、网络或其他来源中加载类的字节码,并将其转换为可执行的Java对象。类加载器…...

CSS中如何实现元素之间的间距(Margin)合并效果?
聚沙成塔每天进步一点点 ⭐ 专栏简介⭐ 外边距合并的示例:⭐ 如何控制外边距合并:⭐ 写在最后 ⭐ 专栏简介 前端入门之旅:探索Web开发的奇妙世界 记得点击上方或者右侧链接订阅本专栏哦 几何带你启航前端之旅 欢迎来到前端入门之旅ÿ…...

【实操干货】如何开始用Qt Widgets编程?(三)
Qt 是目前最先进、最完整的跨平台C开发工具。它不仅完全实现了一次编写,所有平台无差别运行,更提供了几乎所有开发过程中需要用到的工具。如今,Qt已被运用于超过70个行业、数千家企业,支持数百万设备及应用。 在本文中࿰…...

基于深度学习的图像风格迁移发展总结
前言 本文总结深度学习领域的图像风格迁移发展脉络。重点关注随着GAN、CUT、StyleGAN、CLIP、Diffusion Model 这些网络出现以来,图像风格迁移在其上的发展。本文注重这些网络对图像风格迁移任务的影响,以及背后的关键技术和研究,并总结出一…...
小程序页面间有哪些传递数据的方法?
使用全局变量实现数据传递 在 app.js 文件中定义全局变量 globalData, 将需要存储的信息存放在里面使用的时候,直接使用 getApp() 拿到存储的信息 App({// 全局变量globalData: {userInfo: null} }) 使用 wx.navigateTo 与 wx.redirectTo 的时候&…...

基于Flask实现的医疗保险欺诈识别监测模型
基于Flask实现的医疗保险欺诈识别监测模型 项目截图 项目简介 社会医疗保险是国家通过立法形式强制实施,由雇主和个人按一定比例缴纳保险费,建立社会医疗保险基金,支付雇员医疗费用的一种医疗保险制度, 它是促进社会文明和进步的…...

使用分级同态加密防御梯度泄漏
抽象 联邦学习 (FL) 支持跨分布式客户端进行协作模型训练,而无需共享原始数据,这使其成为在互联和自动驾驶汽车 (CAV) 等领域保护隐私的机器学习的一种很有前途的方法。然而,最近的研究表明&…...
将对透视变换后的图像使用Otsu进行阈值化,来分离黑色和白色像素。这句话中的Otsu是什么意思?
Otsu 是一种自动阈值化方法,用于将图像分割为前景和背景。它通过最小化图像的类内方差或等价地最大化类间方差来选择最佳阈值。这种方法特别适用于图像的二值化处理,能够自动确定一个阈值,将图像中的像素分为黑色和白色两类。 Otsu 方法的原…...

Python爬虫(一):爬虫伪装
一、网站防爬机制概述 在当今互联网环境中,具有一定规模或盈利性质的网站几乎都实施了各种防爬措施。这些措施主要分为两大类: 身份验证机制:直接将未经授权的爬虫阻挡在外反爬技术体系:通过各种技术手段增加爬虫获取数据的难度…...
Spring Boot+Neo4j知识图谱实战:3步搭建智能关系网络!
一、引言 在数据驱动的背景下,知识图谱凭借其高效的信息组织能力,正逐步成为各行业应用的关键技术。本文聚焦 Spring Boot与Neo4j图数据库的技术结合,探讨知识图谱开发的实现细节,帮助读者掌握该技术栈在实际项目中的落地方法。 …...
聊一聊接口测试的意义有哪些?
目录 一、隔离性 & 早期测试 二、保障系统集成质量 三、验证业务逻辑的核心层 四、提升测试效率与覆盖度 五、系统稳定性的守护者 六、驱动团队协作与契约管理 七、性能与扩展性的前置评估 八、持续交付的核心支撑 接口测试的意义可以从四个维度展开,首…...
Spring是如何解决Bean的循环依赖:三级缓存机制
1、什么是 Bean 的循环依赖 在 Spring框架中,Bean 的循环依赖是指多个 Bean 之间互相持有对方引用,形成闭环依赖关系的现象。 多个 Bean 的依赖关系构成环形链路,例如: 双向依赖:Bean A 依赖 Bean B,同时 Bean B 也依赖 Bean A(A↔B)。链条循环: Bean A → Bean…...
【JavaSE】多线程基础学习笔记
多线程基础 -线程相关概念 程序(Program) 是为完成特定任务、用某种语言编写的一组指令的集合简单的说:就是我们写的代码 进程 进程是指运行中的程序,比如我们使用QQ,就启动了一个进程,操作系统就会为该进程分配内存…...

【Linux系统】Linux环境变量:系统配置的隐形指挥官
。# Linux系列 文章目录 前言一、环境变量的概念二、常见的环境变量三、环境变量特点及其相关指令3.1 环境变量的全局性3.2、环境变量的生命周期 四、环境变量的组织方式五、C语言对环境变量的操作5.1 设置环境变量:setenv5.2 删除环境变量:unsetenv5.3 遍历所有环境…...
Bean 作用域有哪些?如何答出技术深度?
导语: Spring 面试绕不开 Bean 的作用域问题,这是面试官考察候选人对 Spring 框架理解深度的常见方式。本文将围绕“Spring 中的 Bean 作用域”展开,结合典型面试题及实战场景,帮你厘清重点,打破模板式回答,…...