I understand golang does not support inheritance, but what is the right way to do in go for the following?
type CommonStruct struct{
ID string
}
type StructA struct{
CommonStruct
FieldA string
}
type StructB struct{
CommonStruct
FieldB string
}
func (s *CommonStruct) enrich(){
s.ID = IDGenerator()
}
how I can reuse the code in enrich for all other "sub struct" if the following function?
func doSomthing(s *CommoStruct){
s.enrich()
}
You can use an interface:
type MyInterface interface {
enrich()
}
func doSomthing(s MyInterface){
s.enrich()
}
Any struct that has each of the functions or methods of an interface defined is considered an instance of said interface. You could now pass anything with a CommonStruct
to doSomething()
, since CommonStruct
defined enrich()
. If you want to override enrich()
for a particular struct, simply define enrich()
for that struct. For example:
type CommonStruct struct{
ID string
}
type StructA struct{
*CommonStruct
}
type StructB struct{
*CommonStruct
}
type MyInterface interface {
enrich()
}
func doSomething(obj MyInterface) {
obj.enrich()
}
func (this *CommonStruct) enrich() {
fmt.Println("Common")
}
func (this *StructB) enrich() {
fmt.Println("Not Common")
}
func main() {
myA := &StructA{}
myB := &StructB{}
doSomething(myA)
doSomething(myB)
}
Prints:
Common
Not Common
Test it here!.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With