Like other high-level languages, Golang also supports object-oriented programming, is relatively simple to support, some features are not supported, but sufficient
Interface
The interface uses the interface keyword declaration, any class that implements the interface definition method can instantiate the interface, there is no dependency between the interface and the implementation class, you can implement a new class as Sayer to use, without relying on the Sayer interface, or you can create a new interface for the existing class. Without having to modify any of the existing code, compared to other static languages, this can be considered a golang feature.
type Sayer interface { Say(message string) SayHi()}
Inherited
Inheritance uses a combination of ways to implement
type Animal struct { Name string}func (a *Animal) Say(message string) { fmt.Printf("Animal[%v] say: %v\n", a.Name, message)}type Dog struct { Animal}
Dog will inherit Animal's Say method, with its member Name
Covered
Subclasses can re-implement methods of the parent class
// override Animal.Sayfunc (d *Dog) Say(message string) { fmt.Printf("Dog[%v] say: %v\n", d.Name, message)}
Dog.say will cover Animal.say
Polymorphic
An interface can be instantiated with any pointer that implements the interface
var sayer Sayersayer = &Dog{Animal{Name: "Yoda"}}sayer.Say("hello world")
But it does not support the parent pointer pointing to the subclass, which is not allowed
var animal *Animalanimal = &Dog{Animal{Name: "Yoda"}}
The same subclass inherits the method of the parent class that references the other methods of the parent class and does not have a polymorphic attribute
func (a *Animal) Say(message string) { fmt.Printf("Animal[%v] say: %v\n", a.Name, message)}func (a *Animal) SayHi() { a.Say("Hi")}func (d *Dog) Say(message string) { fmt.Printf("Dog[%v] say: %v\n", d.Name, message)}func main() { var sayer Sayer sayer = &Dog{Animal{Name: "Yoda"}} sayer.Say("hello world") // Dog[Yoda] say: hello world sayer.SayHi() // Animal[Yoda] say: Hi}
In the above code, the subclass Dog does not implement the Sayhi method, calls from the parent class Animal.sayhi, and Animal.sayhi calls the Animal.say Rather than Dog.say, this differs from other object-oriented languages and requires special attention, but you can implement similar functionality in the following ways to improve the reusability of your code
func SayHi(s Sayer) { s.Say("Hi")}type Cat struct { Animal}func (c *Cat) Say(message string) { fmt.Printf("Cat[%v] say: %v\n", c.Name, message)}func (c *Cat) SayHi() { SayHi(c)}func main() { var sayer Sayer sayer = &Cat{Animal{Name: "Jerry"}} sayer.Say("hello world") // Cat[Jerry] say: hello world sayer.SayHi() // Cat[Jerry] say: Hi}
Reference links
- Complete code reference: https://github.com/hatlonely/...
Reprint please indicate the source
This article link: http://www.hatlonely.com/2018 ...