Go 语言中的多态性 [英] Polymorphism in Go lang
问题描述
我正在学习 go lang,我想知道是否有办法做这样的事情:
I am learning go lang and i was wondering if there is a way to do something like this:
type Foo struct {
...
}
type Bar struct {
Foo
...
}
func getFoo() Foo {
return Bar{...}
}
在面向对象的语言中,这样的代码应该可以正常工作,但是在 go 中它会抛出一个错误,说 getFoo()
必须返回类 Foo 的实例.
In an object oriented language, such code should work without problems, but in go it throws me an error, saying that getFoo()
must return an instance of class Foo.
有没有办法实现类似于我在 Go 中描述的多态性?
Is there a way to do polymorphism similar to what i've described in Go?
推荐答案
Go 不是典型的 OO 语言.此外,每种语言都有自己的做事方式.您可以使用界面和合成来实现您想要的,如下所示:
Go is not a typical OO language. Also each language has it own way of doing things. You can use interface and composition to achieve what you desire to, as shown below:
package main
import "fmt"
type Foo interface {
printFoo()
}
type FooImpl struct {
}
type Bar struct {
FooImpl
}
type Bar2 struct {
FooImpl
}
func (f FooImpl)printFoo(){
fmt.Println("Print Foo Impl")
}
func getFoo() Foo {
return Bar{}
}
func main() {
fmt.Println("Hello, playground")
b := getFoo()
b.printFoo()
}
http://play.golang.org/p/iR8QkD3DnP
这篇关于Go 语言中的多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!