I am a golang newbie so pardon me if there is something obvious I am missing. I have the following structures:
type base interface {
func1()
func2()
common_func()
}
type derived1 struct {
base // anonymous meaning inheritence
data DatumType
}
type derived2 struct {
base // anonymous meaning inheritence
data DatumType
}
Now I want to do the following:
data DatumType
' with base
in some way so that looking at the definition of base
one can know what data is common to all structs.common_func()
in one place so that the derived structs don't need to do it.I tried implementing the function with the interface but it fails compilation. I tried to create a struct and inherit from that but am not finding good ways to do that. Is there some clean way out ?
Go does not have inheritance. Instead it offers the concept of embedding.
In this case you don't need/want to define base
as an interface
. Make it a struct and define the functions as methods. Then embedding base
in your derived structs will give them those methods.
type base struct{
data DatumType
}
func (b base) func1(){
}
func (b base) func2(){
}
func (b base) common_func(){
}
type derived1 struct {
base // anonymous meaning embedding
}
type derived2 struct {
base // anonymous meaning embedding
}
Now you can do:
d := derived1{}
d.func1()
d.func2()
d.common_func()
And (as pointed out by David Budworth in the comment) you can access the fields of base
by referring to it's type name like so:
d.base.data = something
There is no inheritance in Go. Use composition:
type common struct {
data DatumType
}
func (c *common) commonFunc() {
// Do something with data.
}
type derived1 struct {
common
otherField1 int
}
// Implement other methods on derived1.
type derived2 struct {
common
otherField2 string
}
// Implement other methods on derived2.