Home  >  Article  >  Backend Development  >  How to implement polymorphism in golang language

How to implement polymorphism in golang language

WJ
WJOriginal
2020-06-09 17:09:013972browse

How to implement polymorphism in golang language

How to implement polymorphism in golang language?

Polymorphism in C is one of its three major features, so how do we implement polymorphism in golang?

There is an interface type interface in golang. Any type can be assigned a value as long as it implements the interface type. If the interface type is empty, then all types implement it. Because it is empty.

Polymorphism in golang is implemented using interface types, that is, defining an interface type and declaring some functions to be implemented. Note that only declarations are required, not implementations,

例如:type People interface {
    // 只声明
    GetAge() int 
    GetName() string 
}

Then you You can define your structure to implement the functions declared in it, and your structure object can be assigned to the interface type.

Written a test program:

package main
import (
    "fmt"
)
type Biology interface {
    sayhi()
}
type Man struct {
    name string
    age  int
}
type Monster struct {
    name string
    age  int
}
func (this *Man) sayhi()  { // 实现抽象方法1
    fmt.Printf("Man[%s, %d] sayhi\n", this.name, this.age)
}
func (this *Monster) sayhi()  { // 实现抽象方法1
    fmt.Printf("Monster[%s, %d] sayhi\n", this.name, this.age)
}
func WhoSayHi(i Biology) {
    i.sayhi()
}
func main() {
    man := &Man{"我是人", 100}
    monster := &Monster{"妖怪", 1000}
    WhoSayHi(man)
    WhoSayHi(monster)
}

Running results:

Man[I am a human, 100] sayhi

Monster[Monster, 1000] sayhi

Related recommendations:Golang tutorial

The above is the detailed content of How to implement polymorphism in golang language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to set font in golangNext article:How to set font in golang