当前位置:网站首页>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 code
The 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 code
As 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 code
Go 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 code
You 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 code
So, 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
边栏推荐
猜你喜欢
随机推荐
C语言学习概览(三)
Srping bean in the life cycle
Delphi MDI appliction 文档最大化显示、去掉最大化最小化等按钮
LeetCode240+312+394
POJ1287联网题解
从购买服务器到网站搭建成功保姆级教程~超详细
根据指定区域内容生成图片并进行分享总结
请问用flinksql写入数据到clickhouse需要引入什么依赖吗?
Golang: go to connect and use mysql
零代码网站开发利器:WordPress
pytest接口自动化测试框架 | 执行失败跳转pdb
POJ1251丛林之路题解
LabVIEW中局部变量和全局变量的分配
企业员工人事管理系统(数据库课设)
Vim简介
Detailed explanation of the crawler framework Scrapy
Offer刷题——1
LeetCode240+312+394
Fist game copyright-free music download, League of Legends copyright-free music, can be used for video creation, live broadcast
curl (7) Failed connect to localhost8080; Connection refused