上海网站建设 美橙/湖南好搜公司seo
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 
idea启动正常,打成jar包时,启动报错
背景 自己写了个小程序,在idea中启动正常,达成jar包发布时,启动报错。 Caused by: java.sql.SQLException: unknown jdbc driver : at com.alibaba.druid.util.JdbcUtils.getDriverClassName(JdbcUtils.java:517) 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 的时候&…...

bh002- Blazor hybrid / Maui 保存设置快速教程
1. 建立工程 bh002_ORM 源码 2. 添加 nuget 包 <PackageReference Include"BootstrapBlazor.WebAPI" Version"7.*" /> <PackageReference Include"FreeSql" Version"*" /> <PackageReference Include"FreeSql.…...

同源政策与CORS
CORS意为跨源资源共享(Cross origin resource sharing),它是一个W3C标准,由一系列HTTP Header组成,这些 HTTP Header决定了浏览器是否允许JavaScript 代码成功获得跨源请求的服务器响应。 在说CORS之前,先…...

科技资讯|三星再申请智能戒指商标,智能穿戴进入更小型化发展
三星正在积极扩展可穿戴设备生态,近日向英国知识产权局提交了名为“Samsung Curio”的新商标,其分类为“Class 9”,可能会用于未来的智能戒指。 智能戒指: 可穿戴计算机本质上的智能手环、智能项链、智能眼镜和智能戒指࿱…...

HarmonyOS开发第一步,熟知开发工具DevEco Studio
俗话说的好,工欲善其事,必先利其器,走进HarmonyOS第一步,开发工具必须先行,当然了,关于开发工具的使用,官网和其他的博客也有很多的讲解,但是并没有按照常用的功能进行概述ÿ…...

【应急响应】Linux常用基础命令
文章目录 文件和目录操作文件内容查看和编辑系统信息查询权限管理进程管理网络管理 文件和目录操作 ls:列出目录内容(例如 ls -l 显示详细信息) cd:切换工作目录 pwd:显示当前工作目录 touch:创建空文件&a…...

什么是Pytorch?
当谈及深度学习框架时,PyTorch 是当今备受欢迎的选择之一。作为一个开源的机器学习库,PyTorch 为研究人员和开发者们提供了一个强大的工具来构建、训练以及部署各种深度学习模型。你可能会问,PyTorch 是什么,它有什么特点…...

Baidu World 2023,定了!
1. 定了,Baidu World 2023 终于定了,今年的 Baidu World 将会于 2023-10-17 日在北京首钢园正式召开,主题为『生成未来 / PROMPT THE WORLD』,这也是近4年来 Baidu World 再次恢复线下举行。 有些小伙伴们如果还不知道什么是 Baid…...

ProxySQL+MGR高可用搭建
服务器点位 NODEIPmgr_node0192.165.26.200mgr_node1192.165.25.201mgr_node2192.165.26.202proxysql192.165.26.199 修改主机名 # 登录192.165.26.200 hostnamectl set-hostname mgr_node0 # 登录192.165.26.201 hostnamectl set-hostname mgr_node1 # 登录192.165.26.202 …...

【Unity小技巧】在Unity中实现类似书的功能(附git源码)
文章目录 前言本文实现的最终效果素材1. 页面素材2. 卡片内容素材地址 翻页实现1. 配置我们的canvas参数2. 添加封面和页码3. 翻页效果4. 添加按钮5. 脚本控制6. 运行效果 页面内容1. 添加卡片内容2. shader控制卡片背面3. 页面背面显示不同卡片 源码参考完结 前言 欢迎来到游…...

STM32设置为I2C从机模式(HAL库版本)
STM32设置为I2C从机模式(HAL库版本) 目录 STM32设置为I2C从机模式(HAL库版本)前言1 硬件连接2 软件编程2.1 步骤分解2.2 测试用例 3 运行测试3.1 I2C连续写入3.2 I2C连续读取3.3 I2C单次读写测试 4 总结 前言 我之前出过一篇关于…...