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

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.斐波那契&#xff1a; #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函数是一种典型的单目计算函数&#xff0c;与其相应的还有指数函数、三角函数等。对于单目计算函数的硬件加速器设计一般两种简单方法:一种是查找表的方式;一种是使用泰勒级数展开成多项式进行近似计算。这两种方式在设计方…...

数字放大(C++)

系列文章目录 1.进阶的卡沙_睡觉觉觉得的博客-CSDN博客 2. 数1的个数_睡觉觉觉得的博客-CSDN博客 3. 双精度浮点数的输入输出_睡觉觉觉得的博客-CSDN博客 4. 足球联赛积分_睡觉觉觉得的博客-CSDN博客 5. 大减价(一级)_睡觉觉觉得的博客-CSDN博客 6. 小写字母的判断_睡觉觉觉得…...

FOC控制框架图

pmsm电机数学模型以及FOC控制框图&#xff08;开源小项目FOC控制BLDC电机&#xff09;_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…...

腾讯云和阿里云服务器折扣对比_看看哪家划算?

阿里云服务器和腾讯云服务器根据购买时长可以享受一定的优惠折扣&#xff0c;综合对比下来腾讯云折扣更低&#xff0c;阿腾云来对比下阿里云和腾讯云的云服务器根据购买时长可以享受的常规折扣对比&#xff1a; 目录 阿里云和腾讯云折扣对比 阿里云服务器常规折扣 腾讯云服…...

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固定频率的同步降压型转换器&#xff0c;因此具有高达90%以上的充电效率&#xff0c;自身发热量极小。包括完整的充电终止电路、自动再充电和一个达1%的4.2V预设充电电压&#xff0c;内部集成了防反灌保护、输…...

PDF校对工具正式上线,为用户提供卓越的文档校对解决方案

为满足当下对数字化文档校对的精准需求&#xff0c;我们今日正式发布全新的PDF校对工具。经过深入的技术研发与细致的测试&#xff0c;该工具旨在为企业和个人用户带来一个高效且准确的PDF文档校对平台。 PDF校对工具的主要特性&#xff1a; 1.全面性校对&#xff1a;工具支持…...

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&#xff08;美国&#xff09; 2、官⽅⽹站 3、登录ChatGPT ![在这里插入图片描述](https://img-blog.csdnimg.cn/26901096553a4ba0a5c88c49b2601e6a.png 填⼊帐号、密码&#xff0c;点击登录。登录成功&#xff0c;如下 3、和ChatGPT对话 开始…...

idea启动正常,打成jar包时,启动报错

背景 自己写了个小程序&#xff0c;在idea中启动正常&#xff0c;达成jar包发布时&#xff0c;启动报错。 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中&#xff0c;每个类都由类加载器加载&#xff0c;并在运行时被创建为一个Class对象。类加载器负责从文件系统、网络或其他来源中加载类的字节码&#xff0c;并将其转换为可执行的Java对象。类加载器…...

CSS中如何实现元素之间的间距(Margin)合并效果?

聚沙成塔每天进步一点点 ⭐ 专栏简介⭐ 外边距合并的示例&#xff1a;⭐ 如何控制外边距合并&#xff1a;⭐ 写在最后 ⭐ 专栏简介 前端入门之旅&#xff1a;探索Web开发的奇妙世界 记得点击上方或者右侧链接订阅本专栏哦 几何带你启航前端之旅 欢迎来到前端入门之旅&#xff…...

【实操干货】如何开始用Qt Widgets编程?(三)

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

基于深度学习的图像风格迁移发展总结

前言 本文总结深度学习领域的图像风格迁移发展脉络。重点关注随着GAN、CUT、StyleGAN、CLIP、Diffusion Model 这些网络出现以来&#xff0c;图像风格迁移在其上的发展。本文注重这些网络对图像风格迁移任务的影响&#xff0c;以及背后的关键技术和研究&#xff0c;并总结出一…...

小程序页面间有哪些传递数据的方法?

使用全局变量实现数据传递 在 app.js 文件中定义全局变量 globalData&#xff0c; 将需要存储的信息存放在里面使用的时候&#xff0c;直接使用 getApp() 拿到存储的信息 App({// 全局变量globalData: {userInfo: null} }) 使用 wx.navigateTo 与 wx.redirectTo 的时候&…...

变量 varablie 声明- Rust 变量 let mut 声明与 C/C++ 变量声明对比分析

一、变量声明设计&#xff1a;let 与 mut 的哲学解析 Rust 采用 let 声明变量并通过 mut 显式标记可变性&#xff0c;这种设计体现了语言的核心哲学。以下是深度解析&#xff1a; 1.1 设计理念剖析 安全优先原则&#xff1a;默认不可变强制开发者明确声明意图 let x 5; …...

第19节 Node.js Express 框架

Express 是一个为Node.js设计的web开发框架&#xff0c;它基于nodejs平台。 Express 简介 Express是一个简洁而灵活的node.js Web应用框架, 提供了一系列强大特性帮助你创建各种Web应用&#xff0c;和丰富的HTTP工具。 使用Express可以快速地搭建一个完整功能的网站。 Expre…...

【OSG学习笔记】Day 18: 碰撞检测与物理交互

物理引擎&#xff08;Physics Engine&#xff09; 物理引擎 是一种通过计算机模拟物理规律&#xff08;如力学、碰撞、重力、流体动力学等&#xff09;的软件工具或库。 它的核心目标是在虚拟环境中逼真地模拟物体的运动和交互&#xff0c;广泛应用于 游戏开发、动画制作、虚…...

1.3 VSCode安装与环境配置

进入网址Visual Studio Code - Code Editing. Redefined下载.deb文件&#xff0c;然后打开终端&#xff0c;进入下载文件夹&#xff0c;键入命令 sudo dpkg -i code_1.100.3-1748872405_amd64.deb 在终端键入命令code即启动vscode 需要安装插件列表 1.Chinese简化 2.ros …...

第25节 Node.js 断言测试

Node.js的assert模块主要用于编写程序的单元测试时使用&#xff0c;通过断言可以提早发现和排查出错误。 稳定性: 5 - 锁定 这个模块可用于应用的单元测试&#xff0c;通过 require(assert) 可以使用这个模块。 assert.fail(actual, expected, message, operator) 使用参数…...

相机Camera日志分析之三十一:高通Camx HAL十种流程基础分析关键字汇总(后续持续更新中)

【关注我,后续持续新增专题博文,谢谢!!!】 上一篇我们讲了:有对最普通的场景进行各个日志注释讲解,但相机场景太多,日志差异也巨大。后面将展示各种场景下的日志。 通过notepad++打开场景下的日志,通过下列分类关键字搜索,即可清晰的分析不同场景的相机运行流程差异…...

【HTTP三个基础问题】

面试官您好&#xff01;HTTP是超文本传输协议&#xff0c;是互联网上客户端和服务器之间传输超文本数据&#xff08;比如文字、图片、音频、视频等&#xff09;的核心协议&#xff0c;当前互联网应用最广泛的版本是HTTP1.1&#xff0c;它基于经典的C/S模型&#xff0c;也就是客…...

零基础在实践中学习网络安全-皮卡丘靶场(第九期-Unsafe Fileupload模块)(yakit方式)

本期内容并不是很难&#xff0c;相信大家会学的很愉快&#xff0c;当然对于有后端基础的朋友来说&#xff0c;本期内容更加容易了解&#xff0c;当然没有基础的也别担心&#xff0c;本期内容会详细解释有关内容 本期用到的软件&#xff1a;yakit&#xff08;因为经过之前好多期…...

C语言中提供的第三方库之哈希表实现

一. 简介 前面一篇文章简单学习了C语言中第三方库&#xff08;uthash库&#xff09;提供对哈希表的操作&#xff0c;文章如下&#xff1a; C语言中提供的第三方库uthash常用接口-CSDN博客 本文简单学习一下第三方库 uthash库对哈希表的操作。 二. uthash库哈希表操作示例 u…...

【深度学习新浪潮】什么是credit assignment problem?

Credit Assignment Problem(信用分配问题) 是机器学习,尤其是强化学习(RL)中的核心挑战之一,指的是如何将最终的奖励或惩罚准确地分配给导致该结果的各个中间动作或决策。在序列决策任务中,智能体执行一系列动作后获得一个最终奖励,但每个动作对最终结果的贡献程度往往…...