Home>

The problem is caused by a requirement:

web controller, want to create a base class,Then define the action method in the controller of the subclass. The base class has a run function to automatically find the action method of the subclass based on the string.

How to solve it?-Use inheritance

Example analysis inheritance

First of all, this demand is very common.Because of the concept of inheritance in my mind,So take it for granted that this is easy to achieve:

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 the run method in b, and naturally calls the run method of a, and then based on the string "test", I hope to find the test method in b (b is a subclass).

Right from the point of view of inheritance,How about the actual operation?method.isvalid () returns false. Obviously, the test method is not found here.

analyse problem,First of all, the two words "inheritance" are wrong here,The word "inheritance" should not be mentioned in go, I prefer to use the word "nested". b is nested with a, so b.run () here is actually syntactic sugar,B.a.run () is called. The entire environment of run is in a here. Therefore, the test of a cannot be found.

Thanks @hongqirui [email protected] for finding the solution with their help:

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 an interface {} in the parent class to record the child class! !! Then the problem is solved! method.isvalid () returned true.

in conclusion

So to simulate ordinary inheritance in golang,In addition to using nesting,You also need to "register" the child class information in the parent class!

  • Previous Example code of popup closeable mask prompt box based on jQuery
  • Next Complete Bootstrap plugin