Base / Derived Example
OOP concepts in Golang and a simple Base-Derived example
Lucio M. Tato wrote an excellent summary on github comparing golang concepts with classic OOP Golang concepts from an OOP point of view
Below is a example that uses functions as arguments in a Base/Derived relationship.
Base-Derived example with functions as argumentpackage main
import (
"fmt"
)
type (
// a function type that takes an int and returns a bool
TestFunc func(int) bool
Base struct {
Name string
myState TestFunc
}
Derived struct {
Base
}
)
func (b *Base) Init(newState TestFunc) {
b.myState = newState
}
func (b *Base) CallMe(aValue int) bool {
return b.myState(aValue)
}
func (b *Base) doSomethingBase(aVal int) bool {
fmt.Printf("in %s->doSomethingBase(%d)\n", b.Name, aVal)
return false
}
func (d *Derived) doSomethingDerived(aVal int) bool {
fmt.Printf("in %s->doSomethingDerived(%d)\n", d.Name, aVal)
return true
}
func main() {
b := new(Base)
b.Name = "Base"
b.Init(b.doSomethingBase)
b.CallMe(123)
d := new(Derived)
d.Name = "Derived"
d.Init(d.doSomethingBase)
d.CallMe(123)
d.Init(d.doSomethingDerived)
d.CallMe(456)
}
/* output:
in Base->doSomethingBase(123)
in Derived->doSomethingBase(123)
in Derived->doSomethingDerived(456)
*/