Inheritance in Go
In Go, inheritance is emulated by embedding anonymous member of parent struct in the derived struct. Lets say, we have a Mammal and a Fish struct and we want to build a Amphibian struct from these two structs. In Go, you would do it like this:
By embedding anonymous members in a struct, you can access the members of the embedded struct using dot notation directly on the embedding struct.
In OOP languages, inheritance also allows polymorphism, through which instance of a derived class can be assigned to the instance of a parent class. Unfortunately Go doesn’t allow this:
The above code produces following error:
> invalid type assertion: salamander.(Mammal) (non-interface type Amphibian on left)
The embedded anonymous member can be accessed using the syntax
EmbeddingInstance.EmbeddedStruct syntax. This can also be assigned to an instance of embedded struct type.
Ambiguity due to multiple inheritance
When multiple anonymous members are declared in a struct and they have same members, Go cannot uniquely identify which of the members you are referring to. This creates ambiguity:
ambiguous selector salamander.Lips
This ambiguity can be resolved by using full path to the ambiguous member.
Embedding anonymous pointer members
Anonymous pointer to struct can also be embedded into a struct. Anonymous pointer members enable the same kind of inheritance normal embedded non-pointer members provide. But you should make sure you initialize the anonymous pointer member before using it. Failing to do so will give an error like this:
Salamander panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x0 pc=0x2370]
goroutine 1 [running]:
exit status 2
Here is a working example with proper initialization of anonymous pointer members:
Right now, I am not aware of any advantages of using anonymous pointer members. If you know any, please share them in the comments.