Go 语言中的多态性 [英] Polymorphism in Go lang

查看:26
本文介绍了Go 语言中的多态性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆