Search code examples
oopgopolymorphism

Polymorphism in 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{...}
}

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.

Is there a way to do polymorphism similar to what i've described in Go?


Solution

  • 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