Home > Article > Backend Development > 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!