The example of this paper describes the implementation method of Golang inheritance simulation. Share to everyone for your reference, specific as follows:
The problem is caused by a demand:
The controller of the Web, you want to create a base class, and then define the action method in the controller of the subclass, which has a run function that automatically finds the action method of the subclass based on the string.
How to solve it? --With inheritance
Example Analysis inheritance
First of all, this requirement is very common, because of the concept of inheritance in the brain, so assume that this is easy to achieve:
Copy Code code as follows:
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 Inheriting A,b calls the Run method, which naturally invokes the run method to a, and I hope to find the test method in B (b is a subclass) based on string "Test".
From an inherited standpoint, yes, actually. Method. IsValid () returns false. Obviously, the test method here is not found.
Analyze the problem, first here "inherit" two words to use the wrong, in the go should not mention the word "inheritance", I prefer to use the word "nesting". b is nested A, so here's B. Run () is actually a syntactic sugar, which is called B. A.run (). All the environments in run here are in a. So I can't find the test of a.
Thanks to @hongqirui and @ Hai Yi, they found a solution with their help:
Copy Code code as follows:
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 a interface{} record subclass to the parent class!! So the problem will be solved! Method. IsValid () returned true.
Conclusion
So in Golang to simulate ordinary inheritance, in addition to the use of nesting, you also need to "register" in the parent class information!
I hope this article will help you with your go language program.