Are there classes in golang?
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) }
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("我会叫"); } }
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() } }
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics











The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

Resource management in Go programming: Mysql and Redis connect and release in learning how to correctly manage resources, especially with databases and caches...

Automatic deletion of Golang generic function type constraints in VSCode Users may encounter a strange problem when writing Golang code using VSCode. when...
