Golang inheritance simulation example details

  • 2020-06-01 09:58:17
  • OfStack

This article illustrates the implementation of Golang inheritance simulation. I will share it with you for your reference as follows:

The problem arises from one requirement:

controller of web, you want to create a base class and then define the action method in the controller of the subclass. The base class has an run function that automatically finds the action method of the subclass based on the string.

How to solve it? - use inheritance

Example analysis inheritance

First of all, this requirement is very common, and because of the concept of inheritance in mind, it is assumed that it is easy to implement:

package main
import(
    "reflect"
)
type A struct {
}
func (self A)Run() {
    c := reflect.ValueOf(self)
    method := c.MethodByName("Test")
    println(method.IsValid())
}
type B struct {
    A
}
func (self B)Test(s string){
    println("b")
}
func main() {
    b := new(B)
    b.Run()
}

B inherits A and calls Run methods in B will naturally call Run methods in A, then I hope to find Test methods in B (B is a subclass) according to string "Test".

That's true from the inheritance point of view. What about actual operations? method.IsValid () returns false. Obviously, the Test method here is not to be found.

To analyze the problem, first of all, the word "inheritance" is misused here. The word "inheritance" should not be mentioned in go. I prefer to use the word "nesting". B is nested with A, so b.Run () is actually a syntax sugar, calling b.A.Run (). Here the entire environment of Run is in A. So Test of A cannot be found.

Thanks to @hongqirui and @heyi for helping us find a solution:

package main
import(
    "reflect"
)
type A struct {
    Parent interface{}
}
func (self A)Run() {
    c := reflect.ValueOf(self.Parent)
    method := c.MethodByName("Test")
    println(method.IsValid())
}
type B struct {
    A
}
func (self B)Test(s string){
    println("b")
}
func (self B)Run(){
    self.A.Run()
}
func main() {
    b := new(B)
    b.A.Parent = b
    b.Run()
}

Add 1 interface{} record subclass to the parent class!! So the problem is solved! method.IsValid () returns true.

conclusion

So to simulate normal inheritance in golang, in addition to using nesting, you need to "register" the subclass information in the parent class!

I hope this article has been helpful to you in the programming of Go language.


Related articles: