The Go language implements polymorphic functional instances similar to c++

  • 2020-06-03 06:46:10
  • OfStack

preface

As a rising star in programming language, Go language is a good development language, which can learn from others and at the same time lose its individuality and pay attention to operation efficiency and development efficiency at the same time. In the go language, there is no concept of a class, but it can still be used struct+interface The following simple example demonstrates how to use go to simulate the polymorphic behavior in c++.

The sample code


package main
 
 
import "os"
import "fmt"
 
 
type Human interface {
  sayHello()
}
 
 
type Chinese struct {
  name string
}
 
 
type English struct {
  name string
}
 
 
func (c *Chinese) sayHello() {
  fmt.Println(c.name," Say hello, world ")
}
 
 
func (e *English) sayHello() {
  fmt.Println(e.name,"says: hello,world")
}
 
 
func main() {
  fmt.Println(len(os.Args))
   
  c := Chinese{" Wang Xing people "}
  e := English{"jorn"}
  m := map[int]Human{}
   
  m[0] = &c
  m[1] = &e
   
  for i:=0;i<2;i++ {
    m[i].sayHello()
  }
}

conclusion

From the above example, implementing polymorphism like C++ in go is very simple, as long as the same interface is implemented.


Related articles: