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!
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.
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.
"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.
Go does not support inheritance, however, it does support composition. The generic definition of composition is "put together".
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"}
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