当前位置:网站首页>Go supports OOP: use struct instead of class
Go supports OOP: use struct instead of class
2022-08-01 07:26:00 【dj1540225203】
In fact, go is very similar to php and java in object-oriented processing, but go has no class.
Is Go Object Oriented?
There is no concept of Class in Go, it is not a pure object-oriented programming language.
Go has types and methods, and also supports an object-oriented programming style.But there is no type hierarchy structure.Interfaces in Go are types that define a collection of methods. These interfaces are simple and generic to use, and they also support embedding into other types, making it easy to provide something similar but not identical to subclasses.
struct instead of class
Go doesn't have class but has struct , you can add methods to struct.You can also bind data to methods that operate on data.It's like Class.
package modulestype Users struct {Name stringAge intStatus bool}func (u Users) SetUserStatus(){u.Status = false;fmt.Printf("Set the status of %s to %t \n ",u.Name,u.Status)}// main.gopackage mainfunc main(){user := modules.Users{Name: "Tom",Age: 12Status: false}user.SetUserStatus()}Copy codeThe above code defines the structure Users, and then binds a setUserStatus method, in which the properties of the structure can be manipulated.In the mian file, we can initialize a variable user of the User structure, and then operate the method of the variable.This is very similar to Class.
New() function instead of constructor
In C# and Java, a class is created with a constructor that takes no parameters.Then in Go you can use the New() method to play the role of a constructor.
In the demo above, we defined and initialized a variable user of the Users structure.What happens when we define the Users struct with zero values?
package mainfunc main(){var u modules.Usersu.setUserStatus()}// Execute go run main.go and the result is as follows:Set the status to falseCopy codeAs you can see, a variable created with a zero value has no valid name , and there is no name value in the output, just an empty string.In the Java language, we often use constructors to solve this problem, using parameterized constructors to create valid objects.For example, in a Java program:
// in java languagepublic class Users{public string NameUsers(name){this.name = name;}}// useUsers user = new User("Tom")Copy codeGo does not support constructors.To prevent other packages from defining a variable with a zero value when accessing a structure of type Users, it will have an invalid effect.By providing a function named New that initializes the type Users with the desired value.
In Go, it is a convention to name functions that create values of type T as NewT(params).This will act as a constructor.When there is only one type in the package, the convention is to name the function New(params), not NewT(params).
So we use it correctly as follows:
package modulestype users struct {name stringage intstatus bool}func New(name string, age int, status bool) Users {user := users{name, age, status}return user}func (u Users) setUserStatus(){u.status = false;fmt.Printf("Set the status of %s to %t \n ",u.name,u.status)}Copy codeYou can see from the above code:
- We changed the structure Users to private, and its fields are also set to private to prevent access by other external packages.Because we don't need to access the users field from anywhere other than the modules package, unless there are other specific scenarios that require it.
- In addition, a public New function is added, the parameter of this function is the field of the user structure, and returns a newly created user instance.
Use simply calls the New function, which prevents the creation of unusable user struct type values.This is also the only way to create a user.
// usepackage mainfunc main(){user := modules.New("Jack", 30, true)user.setUserStatus()}Copy codeSo, although Go doesn't support class , we can effectively use struct instead of class , and use New function instead of constructor.This enables OOP.
Author: Activist No. 6
Link: https://juejin.cn/post/7120926520662556686
Source: Rare Earth Nuggets
边栏推荐
- 特别数的和
- pytest接口自动化测试框架 | 跳过模块
- 插入排序—直接插入排序和希尔排序
- How to use Photoshop to composite star trail photos, post-processing method of night sky star trail photos
- 史上超强最常用SQL语句大全
- crypto-js uses
- 研发过程中的文档管理与工具
- Data organization -- singly linked list of the linear table
- 好的plm软件有哪些?plm软件排行榜
- I have three degrees, and I have five faces. I was "confessed" by the interviewer, and I got an offer of 33*15.
猜你喜欢

如何使用Photoshop合成星轨照片,夜空星轨照片后期处理方法

USB 协议 (二) 术语

【手撕AHB-APB Bridge】~ AHB地址总线的低两位为什么不用来表示地址呢?

小程序全面屏手势配置案例

「面经分享」西北大学 | 字节 生活服务 | 一面二面三面 HR 面

Datagrip error "The specified database userpassword combination is rejected..."Solutions

NIO编程

仿牛客网项目总结

特别数的和

"By sharing" northwestern university life service | | bytes a second interview on three sides by HR
随机推荐
太厉害了,终于有人能把文件上传漏洞讲的明明白白了
Offer刷题——1
pytest接口自动化测试框架 | 使用函数返回值的形式传入参数值
Srping中bean的生命周期
Monitor the width and height of the parent element, adapt to the size of the plug-in
pytest接口自动化测试框架 | parametrize中ids的用法
Srping bean in the life cycle
NIO programming
研发过程中的文档管理与工具
Golang: go static file processing
LabVIEW中局部变量和全局变量的分配
LevelSequence源码分析
阿里三面:MQ 消息丢失、重复、积压问题,该如何解决?
如何使用Photoshop合成星轨照片,夜空星轨照片后期处理方法
零代码网站开发利器:WordPress
Dart 异常详解
rhcsa 第三次
app 自动化 打开app (二)
Golang: go to connect and use mysql
Fist game copyright-free music download, League of Legends copyright-free music, can be used for video creation, live broadcast