A lot of the basics of Go language, including the installation of Go environment, the grammar of Go language, etc., interested friends can first look at the previous article. Https://www.cnblogs.com/zhangweizhong/category/1275863.html.
Object-oriented in the go language today.
Object-oriented in the Go language
In fact, go is not a purely object-oriented programming language. It does not provide the class keyword, only the struct (struct) type.
In Java or C #, struct (struct) cannot have member functions. However, a struct (struct) in the go language can have a "member function". Methods can be added to structs, similar to implementations of a class.
I personally think that the go language in the object-oriented, in fact, more simple, but also easier to understand.
People who have studied Java or C # should all know that the three basic features of object-oriented are encapsulation, inheritance, and polymorphism. Their definition I'm not going to elaborate here. Now, let's look directly at how object-oriented is implemented in the go language.
1. Package characteristics
Golang the mechanism for distinguishing between public and private attributes is whether the method or property is capitalized, and if the first capitalization method is public, it is private if the first letter is lowercase.
Package Mainimport ' FMT 'type person struct { name string}func (person *person) SetName (name string) { person.name = name}func (person * person) GetInfo () {fmt. Println (Person.name)}func main () {p: = person{"Zhangsan"} p.setname ("Lisi") P.getinfo ()}
2. Inheritance Features
The go language inherits in a way that is anonymous: the Woman struct contains the anonymous field person, and the attribute in person is the Woman object.
Package Mainimport ' FMT 'type person struct { name string}type Woman struct { person Sex string}func main () {woman: = woman{person{"Wangwu"}, "female"} fmt. Println (Woman.name) fmt. Println (Woman.sex)}
3. Polymorphic Properties
Package Mainimport "FMT"type Eater interface { Eat ()}type mans struct {}type Woman struct {}func (man * Mans) Eat () {fmt. Println ("Man Eat")}func (woman *woman) Eat () {fmt. Println ("Woman Eat")}func main () {var e eater Woman: = woman{} man: = man{} e = &Woman e.eat ( ) E = & mane.eat ()}
At last
Above, the go language how to implement the object-oriented simple introduction, in fact, and Java and C # and so on are similar, we can compare to see. In summary, Go has no class, but loosely coupled type, method to interface implementation.