How should this code snippet look like in Go? How can I access to method of child class from parent class when child class is not defined yet?
class Parent {
abstract class MyParent {
abstract function doSomething();
function internal() {
return static::doSomething();
}
}
class MyChild extends MyParent {
function doSomething() {
return 'Test';
}
}
//It's called interface
type Parent interface{
doSomething() string
}
//Use interface before defining implementation
func JustPrint(p Parent){
fmt.Println(p.doSomething())
}
//Define MyChild
type MyChild SomeType
//You do not have to implement interface explicitly
//Just to define method needed would be enough
func (mc MyChild) doSomething() string{
return "Test"
}
As @icza said, there's no inheritance in Go (which is a sweet spot). The closest would be embedding a Parent's type.
type Parent struct {}
func (p *Parent) doSomething() {
fmt.Println("Test")
}
type MyChild struct {
Parent
}
func main() {
child := &MyChild{}
child.doSomething() // print "Test"
}
Check out https://golang.org/doc/effective_go.html#embedding
I believe what you are trying to accomplish, in the end, is something akin to the "Template method" design pattern:
In software engineering, the template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in a method, called template method, which defers some steps to subclasses.
https://en.wikipedia.org/wiki/Template_method_pattern
AFAIK, the only correct way to achieve something like this in Go is to use interfaces as @pie-o-pah and @icza have said. I say "something like", because you cannot define methods with interfaces as receivers (i.e. there is no such thing as partially abstract type in Go).
A correct implementation would look like this:
package main
import "fmt"
// --------------------------
// define your purely abstract type as an interface
type MyParent interface {
doSomething() string
}
// define a function (your template method) which operates
// on that interface; an interface cannot be a function receiver,
// but it can always be a parameter
func internal(m MyParent) string {
return m.doSomething()
}
// define the implementation
type MyChild struct {}
// implement the methods for the interface
func (m *MyChild) doSomething() string {
return "Test"
}
// in Go any type which implements all methods in a given interface
// implements that interface implicitly, but you can "force" the
// compiler to check that for you using the following trick
// (basically try to assign a an instance of the interface to a variable,
// then discard it)
var _ MyParent = (*MyChild)(nil)
// -------------------------------
// test code
func main() {
m := &MyChild{}
fmt.Println(m.doSomething())
fmt.Println(internal(m))
}