SoFunction
Updated on 2025-03-05

Detailed explanation of Golang inheritance simulation example

This article describes the Golang inheritance simulation implementation method. Share it for your reference, as follows:

The problem is caused by a requirement:

The web controller hopes to create a base class and then define an action method in the subclass controller. The base class has a run function that can automatically find the action method of the subclass based on the string.

How to solve it? ----Inheritance

Example analysis inheritance

First of all, this requirement is very common. Since there is a concept of inheritance in your mind, I take it for granted that this is easy to implement:

Copy the codeThe code is as follows:
package main
import(
    "reflect"
)
type A struct {
}
func (self A)Run() {
    c := (self)
    method := ("Test")
    println(())
}
type B struct {
    A
}
func (self B)Test(s string){
    println("b")
}
func main() {
    b := new(B)
    ()
}

B inherits A. When B calls the Run method in B, it will naturally call the Run method of A. Then, based on string "Test", I hope to find the Test method in B (B is a subclass).

It’s right from the perspective of inheritance, what’s the actual operation? () Returns false. Obviously, the Test method here is not found.

To analyze the problem, first of all, the word "inheritance" is used wrongly. The word "inheritance" should not be mentioned in Go, but I chose to use the word "nesting". B is nested with A, so the () here is actually syntactic sugar, and the call is (). All the environments of Run here are in A. So you can't find A's Test.

Thanks to @hongqirui and @Haiyi, they found the solution with their help:

Copy the codeThe code is as follows:
package main
import(
    "reflect"
)
type A struct {
    Parent interface{}
}
func (self A)Run() {
    c := ()
    method := ("Test")
    println(())
}
type B struct {
    A
}
func (self B)Test(s string){
    println("b")
}
func (self B)Run(){
    ()
}
func main() {
    b := new(B)
    = b
    ()
}

Add an interface{} record subclass to the parent class! ! This will solve the problem! () returned true.

in conclusion

Therefore, in golang, in addition to using nesting, you also need to "register" the information of the subclass in the parent class!

I hope this article will be helpful to everyone's Go language programming.