Go provides excellent concurrent support, but go does not support full object-oriented support. This does not mean that go does not support object-oriented design. In addition, Go's OO system is very lightweight and the learning cost is minimized. Although go has lost some oo convenience features to achieve this lightweight object-oriented approach, higher efficiency and the number of returned values make up for this.
Languages that fully support Object-Oriented Programming generally have inherited functions. Inheritance has great advantages. The simplest way is to write less code. Of course, inheritance not only saves you a few mouse clicks on the keyboard, but also better abstracts the relationships between various types in the program.
The OO system of Go does not support inheritance, but it can be called"Combination"To implement inheritance. The following shows two programs. After reading them, you will understand this combination technique of go.
Inheritance in C ++:
# Include <iostream> using namespace STD; class person {public: void say () ;}; void person: Say () {cout <"I'm a person. "<Endl ;}// inherit class student: public person {}; int main () {student s; S. say (); Return 0 ;}
Equivalent go program:
Package maintype person struct {} func (p * person) Say () {println ("I'm a person. ")} // combination type student struct {person} func main () {var s student s. say ()}
After the two programs run, the results are:
I'm a person.
It can be seen that go can "inherit" all its behaviors by combining another type, which is very intuitive. However, the meanings of the two codes of C ++ and go are slightly different. Class inheritance of C ++ indicates that person is a parent class of student and hasHierarchy.However, the combination of Go expresses that student is an individual, so studentIncludeStudent can do all the actions of a person. Student is also an individual.
Whether it is inheritance or combination, the "copy" behavior can be rewritten ~
I hope this blog article will help you learn the combination of go.
If reprinted please indicate the source: http://blog.csdn.net/gophers
How does go implement inheritance using combinations?