The Go interviewer asked me how to achieve object-oriented?

煎鱼
中文

Hello everyone, I am fried fish.

When you first get acquainted with the Go language, you will always compare the basic features of other languages to the Go language. To put it bluntly, the old knowledge and the new knowledge are related to achieve higher learning efficiency.

图片

The most common analogy is "How does the Go language implement object-oriented?", a further development is how the Go language implements the inheritance of object-oriented features.

This is not only used in learning, but also in the Go interview in the industry, many interviewers like to ask:

图片

From the reader WeChat group

In today's article, fried fish will take you to understand this knowledge in detail. Let's happily start the road of fish-sucking together.

What is object-oriented

Before understanding whether the Go language is object-oriented (abbreviated: OOP), we must first know what OOP is, and we must first "define" it.

According to the definition of Wikipedia, we sort out several basic cognitions of OOP:

  • Object-oriented programming (OOP) is a programming paradigm based on the concept of "object", which can contain data and code: data exists in the form of fields (usually called attributes or attributes), and code exists in the form of programs (usually called method).
  • The object's own program can access and frequently modify its own data fields.
  • An object is often defined as an instance of a class.
  • Objects use the private/protected/public visibility of properties and methods, and the internal state of the object is protected from outside influences (encapsulated).

Based on these basic cognitions, the three basic characteristics of object-oriented are extended in one step:

  • Package.
  • inherit.
  • Polymorphic.

At this point, the explanation of the basic concepts of object-oriented is over, and those who want to know more can surf the Internet by themselves.

Is Go an object-oriented language

"Is the Go language an object-oriented language?" This is a Nikkei topic. The answer given by the official FAQ is:

图片

Yes, it is not. The reason is:

  • Go has types and methods, and allows an object-oriented programming style, but there is no type hierarchy.
  • The "interface" concept in Go provides a different approach, which we believe is easy to use and more general in some respects. There are also ways to embed types in other types to provide similar things, but not equivalent to subclasses.
  • Methods in Go are more general than methods in C++ or Java: they can be defined for any type of data, even built-in types such as ordinary, "unboxed" integers. They are not limited to structures (classes).
  • Due to the lack of type hierarchy in Go, "objects" in Go are lighter than languages such as C++ or Java.

Go implements object-oriented programming

Encapsulation

The "encapsulation" in object-oriented refers to the ability to hide the internal properties and implementation details of the object, and only provide public interface calls to the outside, so that sub-users do not need to pay attention to how you internally implement it.

The attribute access permissions in the Go language are controlled by the capitalization of the first letter:

  • The first letter is capitalized, which means it is public and can be accessed externally.
  • The first letter is lowercase, which means it is private and cannot be accessed from outside.

Examples of Go language are as follows:

type Animal struct {
 name string
}

func NewAnimal() *Animal {
 return &Animal{}
}

func (p *Animal) SetName(name string) {
 p.name = name
}

func (p *Animal) GetName() string {
 return p.name
}

In the above example, we declared a structure Animal , and its attribute name is lowercase. There is no way to use external methods. Setter and Getter methods exist on the package for unified access and setting control.

In this way, the basic encapsulation in the Go language is realized.

inherit

"Inheritance" in object-oriented refers to that the subclass inherits the characteristics and behaviors of the parent class, so that the subclass object (instance) has the instance domain and methods of the parent class, or the subclass inherits methods from the parent class, so that the subclass has the parent class. The same behavior.

图片

The picture comes from the network

From a practical example, animals are a big parent category, which can be further subdivided into "herbivores" and "carnivores". These two will contain the basic definition of the parent category "animal".

In the Go language, there is no extends keyword, and the combination method is adopted in the language design:

type Animal struct {
 Name string
}

type Cat struct {
 Animal
 FeatureA string
}

type Dog struct {
 Animal
 FeatureB string
}

In the above example, we declared the Cat and Dog structures, which anonymously combined the Animal structure internally. Therefore, both instances of Cat and Dog can call the method of the Animal

func main() {
 p := NewAnimal()
 p.SetName("煎鱼,记得点赞~")

 dog := Dog{Animal: *p}
 fmt.Println(dog.GetName())
}

At the same time Cat and Dog can have their own methods:

func (dog *Dog) HelloWorld() {
 fmt.Println("脑子进煎鱼了")
}

func (cat *Cat) HelloWorld() {
 fmt.Println("煎鱼进脑子了")
}

The above example can normally include Animal , and can also have its own independent properties and methods, achieving a similar inheritance effect in the Go language.

Polymorphism

"Polymorphism" in object-oriented refers to the ability of the same behavior to have multiple different manifestations or forms. Specifically, it refers to the same method of a class instance (object) with different manifestations in different situations.

Polymorphism also allows objects with different internal structures to share the same external interface, that is, they are all a set of external templates. What is actually inside, as long as it meets the specifications.

In Go language, polymorphism is achieved through interfaces:

type AnimalSounder interface {
 MakeDNA()
}

func MakeSomeDNA(animalSounder AnimalSounder) {
 animalSounder.MakeDNA()
}

In the above example, we declared an interface type AnimalSounder , supporting a MakeSomeDNA method, which accepts the AnimalSounder interface type as input parameters.

So in the Go language. As long as the matching Cat and Dog instances also implement the MakeSomeDNA method, then we can consider it to be the AnimalSounder interface type:

type AnimalSounder interface {
 MakeDNA()
}

func MakeSomeDNA(animalSounder AnimalSounder) {
 animalSounder.MakeDNA()
}

func (c *Cat) MakeDNA() {
 fmt.Println("煎鱼是煎鱼")
}

func (c *Dog) MakeDNA() {
 fmt.Println("煎鱼其实不是煎鱼")
}

func main() {
 MakeSomeDNA(&Cat{})
 MakeSomeDNA(&Dog{})
}

When the instances of Cat and Dog AnimalSounder interface type, it means that the conditions are met, and they are just one thing in the Go language. It can be passed into the MakeSomeDNA method as an input parameter, and then the polymorphic behavior can be realized according to different instances.

Summarize

Through today’s article, we have a basic understanding of the definition of object-oriented and Go’s official views on object-oriented, and at the same time, we focus on the three major characteristics of object-oriented: "encapsulation, inheritance, polymorphism" in the implementation of the Go language The methods are explained one by one.

In daily work, it is enough to have a basic understanding of these concepts. If it is an interview, you can focus on three characteristics: "encapsulation, inheritance, polymorphism" and the five principles "Single Responsibility Principle (SRP), Open and Closed Principle (OCP), Richter Substitution Principle (LSP), Dependency Inversion Principle (DIP), Interface Isolation Principle (ISP)" for in-depth understanding and explanation.

After the explanation, we will focus on the above-mentioned concepts. Then explain its specific implementation and the basic principles used in the Go language, and combine the explanations with each other to get a good effect.

Encourage

If you have any questions, welcome feedback and exchanges in the comment area. The best relationship between , and likes is fried fish . Thank you for your support.

The article is continuously updated, and you can read it on search [the brain is fried fish], this article 1615fd0ec4eb96 GitHub github.com/eddycjy/blog has been included, welcome to Star to remind you to update.

refer to

  • Is Go an Object Oriented language?
  • Three basic characteristics of object-oriented, five basic principles
  • Go object-oriented programming (translation)
阅读 2.4k

煎鱼的清汤锅
今天写代码了吗 :-) 博客地址:[链接]
7.7k 声望
11.5k 粉丝
0 条评论
7.7k 声望
11.5k 粉丝
文章目录
宣传栏