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

查看:78
本文介绍了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{...}
}

在面向对象的语言中,这样的代码应该可以正常工作,但是在执行过程中会抛出一个错误,说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 lang中的多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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