I am coming to Go from Java and some things confuses me.
For example, let's consider the following code:
package main
import (
"fmt"
)
type I interface {
Do()
MegaDo()
}
type A struct {
}
func (a *A) Do() {
fmt.Println("A")
}
func (a *A) MegaDo() {
a.Do()
}
type B struct {
A
}
func (a *B) Do() {
fmt.Println("B")
}
var i I
func main() {
fmt.Println("Hello, playground")
var i I = &B{}
i.MegaDo()
}
Here we have an interface I
with methods Do()
and MegaDo()
. Struct A
implements both methods and MegaDo
calls Do
internally. And B
is composed over A
and overrides only Do()
If I'll mimic the same code in Java I would expect it to print "B". But in Go it prints "A".
While I, kind of, understand why it happens (because it's embedding and not inheritance) I wonder how I can mimic the same thing in Go. For example I have two implementations of the same interface that differs only a little. How can I maximize code reusage in this case? I can't believe that in order to customize a bit logic in one implementation I have to copy-paste everything and just fix a little part in my code. Maybe there is some idiomatic way to do this in Go?