There are no classes in golang. Golang is not a pure object-oriented programming language. It has no concept of class, and there is no inheritance. However, Go can also simulate object-oriented programming. In Go, struct can be compared to a class in other languages; a structure is defined through struct to represent a type of object, such as "type person struct {...}".
The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.
Three major characteristics of object-oriented: encapsulation, inheritance, and polymorphism.
Go is not a pure object-oriented programming language. It has no concept of class, and there is no inheritance. But Go can also simulate object-oriented programming, that is, struct can be compared to classes in other languages.
Object
Go does not have the concept of class. It defines a structure through struct to represent a type of object.
type person struct { Age int Name string }
Objects are organisms of state and behavior. For example, the following java code:
public class Person { int age; String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Unlike Java, Go's methods do not need to be bound to the class data in a class definition, only need to be defined in the same package. This may seem strange to students who are new to Go.
type person struct { Age int Name string } func (p *person) GetAge() int { return p.Age } func (p *person) SetAge(age int) { p.Age = age } func (p *person) GetName() string { return p.Name } func (p *person) SetName(name string) { p.Name = name }
Constructor
Go does not have a constructor, and the data carrier of the object is a struct. Java supports constructors. The name of the constructor is the same as the class name. Multiple constructors are implemented through function overloading.
The Go constructor is simulated through the factory function. An example is as follows:
type person struct { Age int Name string } /** 构造函数1--通过名字初始化 */ func newPersonByName(name string) *person { return &person{ Name: name, } } /** 构造函数2--通过年龄初始化 */ func newPersonByAge(age int) *person { return &person{ Age: age, } }
It should be noted that the first letter of the name of the person structure should be lowercase to avoid external direct bypass of the simulated constructor
Access permissions
Java has four access rights, as follows:
public | protected |
friendly (default) |
private | |
Same class | yes | yes | yes | yes |
yes | yes | yes | no | |
yes | yes | no | no | |
yes | no | no | no |
Encapsulation
Encapsulation binds the abstracted structure with the functions that operate on the data inside the structure. External programs can only modify the internal state of the structure according to the exported function API (public method). Encapsulation has two benefits: Hidden implementation: We only want users to directly use the API to operate the internal state of the structure without understanding the internal logic. Like an iceberg, we only see the part above the water. Protect data: We can impose security measures on data modification and access. When calling the setter method, we can verify the parameters; when calling the getter method, we can add access logs, etc. A simple bean definition is as follows:type person struct { Age int Name string } func NewPerson(age int, name string) *person{ return &person{age, name} } func (p *person) SetAge(age int) { p.Age = age } func (p *person) SetName(name string) { p.Name = name } func main() { p:= NewPerson(10, "Lily") p.SetName("Lucy") p.SetAge(18) }It should be noted that Go’s method is a special function, which is just a kind of syntax sugar for the compiler. The compiler will take a look Help us pass a reference to the object as the first parameter of the function. For example, the following code is equivalent to
func main() { p:= NewPerson(10, "Lily") p.SetName("Lily1") // 等价于下面的写法 // p是一个引用,函数引用 setNameFunc := (*person).SetName setNameFunc(p, "Lily2") fmt.Println(p.Name) }
inheritance
inheritance. If a subclass inherits the parent class, it will obtain the characteristics and behaviors of the parent class. The main purpose of inheritance is to reuse code. Java's two major tools for code reuse are inheritance and composition. Go has no concept of class, and there is no inheritance. But Go can simulate inheritance through anonymous composition. As shown below, Cat automatically obtains Animal's move() and Shout() methods by anonymously aggregating the Animal structure:type Animal struct { Name string } func (Animal) move() { fmt.Println("我会走") } func (Animal) shout() { fmt.Println("我会叫") } type Cat struct { Animal // 匿名聚合 } func main() { cat := &Cat{Animal{"猫"}} cat.move() cat.shout() }
Polymorphism
Polymorphism, variables declared as base classes, can point to different subclasses during runtime and call methods of different subclasses. The purpose of polymorphism is to achieve uniformity. We implement polymorphism through interfaces. In Java, we define interfaces through interfaces and implement interfaces through implements.interface Animal { void move(); void shout(); } class Dog implements Animal { @Override public void move() { System.out.println("我会走"); } @Override public void shout() { System.out.println("我会叫"); } }Go infers through
duck type that as long as an object looks like a duck and quacks like a duck, then it is a duck. In other words, Go's interface is relatively hidden. As long as an object implements all the methods declared by the interface, it is considered to belong to the interface.
type Animal interface { move() shout() } type Cat struct { Animal // 匿名聚合 } func (Cat)move() { fmt.Println("猫会走") } func (Cat)shout() { fmt.Println("猫会叫") } type Dog struct { Animal // 匿名聚合 } func (Dog)move() { fmt.Println("狗会走") } func (Dog)shout() { fmt.Println("狗会叫") } func main() { cat := Cat{} dog := Dog{} // 申明接口数组 animals := []Animal{cat, dog} for _,ele := range animals { // 统一访问 ele.move() ele.shout() } }【Related recommendations:
Go video tutorial, Programming teaching】
The above is the detailed content of Are there classes in golang?. For more information, please follow other related articles on the PHP Chinese website!

Goisidealforbuildingscalablesystemsduetoitssimplicity,efficiency,andbuilt-inconcurrencysupport.1)Go'scleansyntaxandminimalisticdesignenhanceproductivityandreduceerrors.2)Itsgoroutinesandchannelsenableefficientconcurrentprogramming,distributingworkloa

InitfunctionsinGorunautomaticallybeforemain()andareusefulforsettingupenvironmentsandinitializingvariables.Usethemforsimpletasks,avoidsideeffects,andbecautiouswithtestingandloggingtomaintaincodeclarityandtestability.

Goinitializespackagesintheordertheyareimported,thenexecutesinitfunctionswithinapackageintheirdefinitionorder,andfilenamesdeterminetheorderacrossmultiplefiles.Thisprocesscanbeinfluencedbydependenciesbetweenpackages,whichmayleadtocomplexinitializations

CustominterfacesinGoarecrucialforwritingflexible,maintainable,andtestablecode.Theyenabledeveloperstofocusonbehavioroverimplementation,enhancingmodularityandrobustness.Bydefiningmethodsignaturesthattypesmustimplement,interfacesallowforcodereusabilitya

The reason for using interfaces for simulation and testing is that the interface allows the definition of contracts without specifying implementations, making the tests more isolated and easy to maintain. 1) Implicit implementation of the interface makes it simple to create mock objects, which can replace real implementations in testing. 2) Using interfaces can easily replace the real implementation of the service in unit tests, reducing test complexity and time. 3) The flexibility provided by the interface allows for changes in simulated behavior for different test cases. 4) Interfaces help design testable code from the beginning, improving the modularity and maintainability of the code.

In Go, the init function is used for package initialization. 1) The init function is automatically called when package initialization, and is suitable for initializing global variables, setting connections and loading configuration files. 2) There can be multiple init functions that can be executed in file order. 3) When using it, the execution order, test difficulty and performance impact should be considered. 4) It is recommended to reduce side effects, use dependency injection and delay initialization to optimize the use of init functions.

Go'sselectstatementstreamlinesconcurrentprogrammingbymultiplexingoperations.1)Itallowswaitingonmultiplechanneloperations,executingthefirstreadyone.2)Thedefaultcasepreventsdeadlocksbyallowingtheprogramtoproceedifnooperationisready.3)Itcanbeusedforsend

ContextandWaitGroupsarecrucialinGoformanaginggoroutineseffectively.1)ContextallowssignalingcancellationanddeadlinesacrossAPIboundaries,ensuringgoroutinescanbestoppedgracefully.2)WaitGroupssynchronizegoroutines,ensuringallcompletebeforeproceeding,prev


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6
Visual web development tools
