Yes yes, I know, Golang has no "overriding, polymorphism etc.", you know, what I mean, just composition. @wellsantos After a few months of writing golang code I agree. I know consider Go to have a very good balance between abstraction concepts and speed of invocation due to binding all methods at compilation time.
Since Golang does not support classes, so inheritance takes place through struct embedding. We cannot directly extend structs but rather use a concept called composition where the struct is used to form other objects. So, you can say there is No Inheritance Concept in Golang.
I have the following:
type Base struct {
}
func(base *Base) Get() string {
return "base"
}
func(base *Base) GetName() string {
return base.Get()
}
I want to define a new type with a new implementation of Get() so that I can use the new type in place of Base
and where GetName() is called it calls the new Get() implementation . If I were using Java I would inherit Base and override Get(). How should I achieve this in Go? I want to avoid breaking changes if possible, so existing consumers of Base do not need to be changed.
My first stab at this looks like..
type Sub struct {
Base
}
func(sub *Sub) Get() string {
return "Sub"
}
..which doesn't work. My brain isn't wired for Go yet clearly.
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