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

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


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 {
type Chinese struct {
  name string
type English struct {
  name string
func (c *Chinese) sayHello() {
  fmt.Println(," Say hello, world ")
func (e *English) sayHello() {
  fmt.Println(,"says: hello,world")
func main() {
  c := Chinese{" Wang Xing people "}
  e := English{"jorn"}
  m := map[int]Human{}
  m[0] = &c
  m[1] = &e
  for i:=0;i<2;i++ {


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

Related articles: