Interfaces and Embedding
An interface = type that specifies a set of method signatures. When a concrete type provides definitions for all the methods in an interface, it is said to implement the interface.
Embedding - allows one struct type to include another struct, inheriting the fields and methods of the embedded type. It is Go's mechanism to achieve composition over traditional inheritance.
Embedding provides a way to "inherit" methods.
But it's not inheritance because Go doesn't have the keyword this, also we can't override the embedded's method implementation.
Type embedding isn't inheritance, and pretending it is will lead to bugs.
In Java, this
is a special implicit pointer that always has the runtime type of the class the method was originally invoked on. So Tiger.Greet()
dispatches to Cat.Greet()
, but the latter has a this
pointer of type Tiger
, and so this.Speak()
dispatches to Tiger.Speak()
.
Resources:
Last updated