Object oriented in Go – embedding

Embedding is a mechanism to allow the ability to borrow pieces from different classes. It is the equivalent of multiple inheritance with non-virtual members.

Let's call Basestruct embedded into a Derived struct. Like normal (public/protected) subclassing, the fields and methods of the Base class are directly available in the Derived struct. Internally, a hidden/anonymous field is created with the name of the base struct. The following code sample demonstrates the behavior:

type Bird struct {
     featherLength  int
     classification string
}
type Pigeon struct { Bird Name string }
func main() { p := Pigeon{Name :"Tweety", } p.featherLength = 10 fmt.Println(p) }

Base fields and methods can be shadowed, if redefined in the derived class. Once shadowed, the only way to access the base member is to use the hidden field named as the base-struct-name:

type Bird struct {
    featherLength  int
    classification string
}

type Pigeon struct { Bird featherLength float64 Name string }
func main() { p := Pigeon{Name :"Tweety", } p.featherLength = 3.14
// featherLength refers to the member of the Pigeon struct NOT Bird fmt.Println(p) }

This may feel like inheritance, but embedding does not provide polymorphism. Embedding differs from subclassing in an important way: when a type is embedded, the methods of that type are available as methods of the outer type; however, for invocation of the embedded struct methods, the receiver of the method must be the inner (embedded) type, not the outer one.

Embedding can also be done on interfaces. A famous example of this is the ReaderWriter interface in the Golang stdlib, which combines both the Reader and Writer interface:

type ReadWriter interface {
Reader
Writer
}

Golang allows multiple structures to be embedded inside one. This gives the ability to borrow behavior from multiple classes. This is similar to multiple inheritance. However, a note of caution: there is a reason why languages such as Java avoid multiple inheritance. It's called the deadly diamond of death problem. This problem refers to the ambiguity that arises when two classes, B and C, inherit from A, and a third class, D, inherits from both B and C. Here, if there is a method in A that B and C have overridden but D has not, then it is ambiguous on what exact method version is advertised by D:

That said, in Golang, since embedding essentially means that inherited fields remain in the inheriting struct namespace (struct), the compiler catches any ambiguities.

To know more about method overriding, visit https://en.wikipedia.org/wiki/Method_overriding.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset