GO object-oriented language
In fact, GO is not a pure object-oriented programming language. It did not provide class (class) keyword, provided only a structure (struct) type.
java or C # inside the structure (struct) can not have member functions. However, Go language structure (struct) can have "member functions." The method may be added to the structure, similar to the implementation of a class.
I personally feel that Go in object-oriented language, in fact, simpler and easier to understand.
Learned java or C # people should know, object-oriented three basic characteristics: encapsulation, inheritance, and polymorphism. Their definition I will not elaborate here. Here, take a look directly at the object-oriented language go is how to achieve it.
1. Package Characteristics
Are Golang distinguish between public property and private property mechanism is the method or property capitalize the first letter capitalized if the method is public, if the first letter lowercase word is private.
package main import "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. inherited characteristics
Language of inheritance GO uses a combination of an anonymous: Woman structure contains an anonymous field Person, then the Person of the property will belong to the Woman object.
package main import "fmt" type Person struct { name string } type Woman struct { Person sex string } func main() { woman := Woman{Person{"wangwu"}, "女"} fmt.Println(woman.name) fmt.Println(woman.sex) }
3. Polymorphic characteristics
package main import "fmt" type Eater interface { Eat() } type Man struct { } type Woman struct { } func (man *Man) 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 = &man e.Eat() }
At last
Above, how to put the Go language object-oriented brief moment, in fact, with java and C #, are also similar, we can compare the run. It is the summary: Go does not have classes, but loosely coupled type, method implementation of the interface.