Polymorphism in Go lang
11,414
Solution 1
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
Solution 2
In Go, polymorphism is achieved by implementing 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, anything 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
}
Related videos on Youtube
Author by
areller
Updated on September 14, 2022Comments
-
areller over 1 year
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?
-
dm03514 about 8 yearsI think you could Create and return an interface gobyexample.com/interfaces
-
-
m0meni about 8 yearsI've heard the problem with interface is that it loses compile time type checking, right?
-
driusan about 8 yearsI think you're confusing "interface" with "interface {}".. Go will still type check interfaces at compile time, it'll just check that the variable is an instance of that interface. The problem with "interface{}" is that, since the functions that need to be matched for the interface is the empty set, everything matches it, and you lose compile time type checking.
-
m0meni about 8 years@driusan awesome reply! Thanks
-
Jeff Widman over 4 yearsIt appears
Bar2
is not needed in this example?