SoFunction
Updated on 2025-03-01

Implement polymorphic paradigm operation using go's interface case

Look at the program:

package main 
import "fmt" 
type BaseIntf interface {
 Process()
}
 
type Msg1 struct {
 req int
 rsp int
}
 
func (p *Msg1) Process() {
 ("process 1")
}
 
type Msg2 struct {
 req int
 rsp int
}
 
func (p *Msg2) Process() {
 ("process 2")
}
 
func main() {
 m1 := new(Msg1)
 ()
 
 m2 := new(Msg2)
 ()
}

Change it:

package main 
import "fmt" 
type BaseIntf interface {
 Process()
}
 
func Run(proc BaseIntf) {
 ("run")
 ()
}
 
type Msg1 struct {
 req int
 rsp int
}
 
func (p *Msg1) Process() {
 ("process 1")
} 
 
type Msg2 struct {
 req int
 rsp int
}
 
func (p *Msg2) Process() {
 ("process 2")
} 
 
func main() {
 m1 := new(Msg1)
 Run(m1)
 
 m2 := new(Msg2)
 Run(m2)
}

I have seen this style of code many times.

Not to say much.

Supplement: In go language, polymorphism is implemented through empty interface query

Just look at the code~ The empty interface is the exquisiteness of the Go language

package main
type Person struct {
 name string
 age int
}
type Cat struct {
 kind string
 sex bool
 price int
}
func main() {
 family := make([]interface{},0,10)
 obj1 := &Person{
 name: "Lu Yunfei",
 age: 28,
 }
 obj2 := &Person{
 name: "Hu Jingru",
 age: 18,
 }
 obj3 := &Cat{
 kind: "English short",
 sex: true,
 price: 2000,
 }
 family = append(family, obj1, obj2, obj3)
 for _, value := range family {
 switch obj := value.(type) {
 case *Person:
 print( + "\n")
 case *Cat:
 print( + "\n")
 }
 }
}

The output result is as follows

Lu Yunfei

Hu Jingru

English short

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.