Go本身不具有多态的特性,不能够像Java、C++那样编写多态类、多态方法。但是,使用Go可以编写具有多态功能的类绑定的方法。Go使用struct构建类,根据不同类调用不同的方法, 使用struct对象类型来消除了方法的模糊性。直接撸代码
package ch12
import (
"fmt"
"testing"
)
//实现多态
type Code string
type ProgramDemo interface {
WriteHellWolrd() Code
}
type JavaTypeWrite struct {
}
type GoTypeWrite struct {
}
func (p *JavaTypeWrite)WriteHellWolrd() Code {
return "来源java hello wolrd"
//fmt.Printf("%T %v",p,p.WriteJavaHellWolrd("来源java hello wolrd"))
}
func (p *GoTypeWrite)WriteHellWolrd() Code {
return "来源Go hello wolrd"
//fmt.Printf("%T %v",p,p.WriteJavaHellWolrd("来源java hello wolrd"))
}
func writeHelloWorld( p ProgramDemo) {
fmt.Printf("%T %v \n",p,p.WriteHellWolrd())
}
func TestDemo( t *testing.T) {
javaHello := new(JavaTypeWrite)
GOHello := new(GoTypeWrite)
writeHelloWorld(javaHello)
writeHelloWorld(GOHello)
}
Git代码地址:https://github.com/yangliuzzu/GO-daily-Study.git