当前位置: 首页 > 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 的时候&…...

SpringBoot-17-MyBatis动态SQL标签之常用标签

文章目录 1 代码1.1 实体User.java1.2 接口UserMapper.java1.3 映射UserMapper.xml1.3.1 标签if1.3.2 标签if和where1.3.3 标签choose和when和otherwise1.4 UserController.java2 常用动态SQL标签2.1 标签set2.1.1 UserMapper.java2.1.2 UserMapper.xml2.1.3 UserController.ja…...

label-studio的使用教程(导入本地路径)

文章目录 1. 准备环境2. 脚本启动2.1 Windows2.2 Linux 3. 安装label-studio机器学习后端3.1 pip安装(推荐)3.2 GitHub仓库安装 4. 后端配置4.1 yolo环境4.2 引入后端模型4.3 修改脚本4.4 启动后端 5. 标注工程5.1 创建工程5.2 配置图片路径5.3 配置工程类型标签5.4 配置模型5.…...

(十)学生端搭建

本次旨在将之前的已完成的部分功能进行拼装到学生端&#xff0c;同时完善学生端的构建。本次工作主要包括&#xff1a; 1.学生端整体界面布局 2.模拟考场与部分个人画像流程的串联 3.整体学生端逻辑 一、学生端 在主界面可以选择自己的用户角色 选择学生则进入学生登录界面…...

AI Agent与Agentic AI:原理、应用、挑战与未来展望

文章目录 一、引言二、AI Agent与Agentic AI的兴起2.1 技术契机与生态成熟2.2 Agent的定义与特征2.3 Agent的发展历程 三、AI Agent的核心技术栈解密3.1 感知模块代码示例&#xff1a;使用Python和OpenCV进行图像识别 3.2 认知与决策模块代码示例&#xff1a;使用OpenAI GPT-3进…...

线程同步:确保多线程程序的安全与高效!

全文目录&#xff1a; 开篇语前序前言第一部分&#xff1a;线程同步的概念与问题1.1 线程同步的概念1.2 线程同步的问题1.3 线程同步的解决方案 第二部分&#xff1a;synchronized关键字的使用2.1 使用 synchronized修饰方法2.2 使用 synchronized修饰代码块 第三部分&#xff…...

理解 MCP 工作流:使用 Ollama 和 LangChain 构建本地 MCP 客户端

&#x1f31f; 什么是 MCP&#xff1f; 模型控制协议 (MCP) 是一种创新的协议&#xff0c;旨在无缝连接 AI 模型与应用程序。 MCP 是一个开源协议&#xff0c;它标准化了我们的 LLM 应用程序连接所需工具和数据源并与之协作的方式。 可以把它想象成你的 AI 模型 和想要使用它…...

在 Nginx Stream 层“改写”MQTT ngx_stream_mqtt_filter_module

1、为什么要修改 CONNECT 报文&#xff1f; 多租户隔离&#xff1a;自动为接入设备追加租户前缀&#xff0c;后端按 ClientID 拆分队列。零代码鉴权&#xff1a;将入站用户名替换为 OAuth Access-Token&#xff0c;后端 Broker 统一校验。灰度发布&#xff1a;根据 IP/地理位写…...

Nuxt.js 中的路由配置详解

Nuxt.js 通过其内置的路由系统简化了应用的路由配置&#xff0c;使得开发者可以轻松地管理页面导航和 URL 结构。路由配置主要涉及页面组件的组织、动态路由的设置以及路由元信息的配置。 自动路由生成 Nuxt.js 会根据 pages 目录下的文件结构自动生成路由配置。每个文件都会对…...

select、poll、epoll 与 Reactor 模式

在高并发网络编程领域&#xff0c;高效处理大量连接和 I/O 事件是系统性能的关键。select、poll、epoll 作为 I/O 多路复用技术的代表&#xff0c;以及基于它们实现的 Reactor 模式&#xff0c;为开发者提供了强大的工具。本文将深入探讨这些技术的底层原理、优缺点。​ 一、I…...

使用Matplotlib创建炫酷的3D散点图:数据可视化的新维度

文章目录 基础实现代码代码解析进阶技巧1. 自定义点的大小和颜色2. 添加图例和样式美化3. 真实数据应用示例实用技巧与注意事项完整示例(带样式)应用场景在数据科学和可视化领域,三维图形能为我们提供更丰富的数据洞察。本文将手把手教你如何使用Python的Matplotlib库创建引…...