Polymorphism in Go lang

I am learning a language 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 it it causes an error saying that getFoo() should return an instance of the Foo class.

Is there a way to make polymorphism similar to what I described in Go?

+8
polymorphism oop go
source share
2 answers

Go is not a typical OO language. Each language also has its own way of doing something. You can use the interface and composition to achieve what you want, 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

+11
source share

In Go, polymorphism is achieved through the implementation of interfaces.

 type Being interface { somemethod() } type Foo struct {} type Bar struct { Foo } type Baz struct { Foo } // `Bar` and `Baz` implement `Being` func (b *Bar) somemethod() {} func (b *Baz) somemethod() {} func getAnyFoo(b *Being) Foo { return b.Foo } 

Therefore, something implements an empty interface.

 type Foo struct {} type Bar struct { Foo } // Get anything and extract its `Foo` if anything is a Bar func getAnyFoo(i interface{}) Foo { // Normally this would need a type switch to check the type mybar := i.(Bar) return mybar.Foo } 
+3
source share

All Articles