Hello! Today, we're exploring a fundamental facet of Go: Composition. Composition is a design principle in Go that enables code reuse. Unlike languages that use inheritance
, Go opts for Composition. This lesson aims to understand Composition and how it applies in Go.
Composition in Go allows for the construction of complex types using simpler ones. In Go's Composition, you frequently encounter terms like Embedding
and Anonymous Fields
. Embedding
involves including one struct inside another, creating a parent-child relationship. Anonymous Fields
are declared in a struct without a name, and their type becomes their name.
In the example above, Point
is an anonymous field in the Circle
.
Now, let's see Composition in action in Go, using structs:
