Are there classes in golang?

青灯夜游
Release: 2023-01-12 16:56:04
Original
3844 people have browsed it

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 {...}".

Are there classes in golang?

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 }
Copy after login

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; } }
Copy after login

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 }
Copy after login

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, } }
Copy after login

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:

##The same package yes yes yes no Different Bao Subclasses yes yes no no Different package non-subclass yes no no no
java access control character
public protected

friendly

(default)

private
Same class yes yes yes yes

Go has simplified it, and the minimum granularity of visibility is the package. In other words, Go retains two types, friendly and public. If the first letter of a Go variable name is lowercase, it means it is visible within the package; if the first letter is uppercase, it means it is visible anywhere.

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) }
Copy after login
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) }
Copy after login

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() }
Copy after login

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("我会叫"); } }
Copy after login
Go infers through

duck typethat 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() } }
Copy after login
【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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!