Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang Method Override

Tags:

People also ask

Is method overriding possible in go?

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.

How do you implement inheritance in Golang?

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.