Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang struct inheritance not working as intended?

Tags:

go

Check out this sandbox

When declaring a struct that inherits from a different struct:

type Base struct {
    a string
    b string
}

type Something struct {
    Base
    c string
}

Then calling functions specifying values for the inherited values gives a compilation error:

f(Something{
    a: "letter a",
    c: "letter c",
})

The error message is: unknown Something field 'a' in struct literal.

This seems highly weird to me. Is this really the intended functionality?

Thanks for the help!

like image 662
beetree Avatar asked Jan 06 '16 22:01

beetree


People also ask

How do you inherit a struct in Go?

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.

Does struct support inheritance?

Structs cannot have inheritance, so have only one type. If you point two variables at the same struct, they have their own independent copy of the data. With objects, they both point at the same variable.

Can struct types be used within an inheritance hierarchy why why not?

"the reason structs cannot be inherited is because they live on the stack is the right one" - no, it isn't the reason. A variable of a ref type will contain a reference to an object in the heap. A variable of a value type will contain the value of the data itself.

Does Go support inheritance or generic?

Go does not support inheritance, however, it does support composition. The generic definition of composition is "put together".


1 Answers

Golang doesn't provide the typical notion of inheritance. What you are accomplishing here is embedding.

It does not give the outer struct the fields of the inner struct but instead allows the outer struct to access the fields of the inner struct.

In order to create the outer struct Something you need to give its fields which include the inner struct Base

In your case:

Something{Base: Base{a: "letter a"}, c: "letter c"}
like image 199
Leo Correa Avatar answered Oct 08 '22 21:10

Leo Correa