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:
Here, the Person
struct is embedded into the Student
struct. We then directly access the Name
field from the Student
struct instance named john
.
Note that we can also access the Name
like this:
In some cases, this can be useful. For example, if the "child" struct has a field named the same as one of the fields of the "parent" struct, it would be a proper way to access it. Consider the following example:
In this case, a student has an embedded school. Both Student
and School
has fields Name
, so here is how we distinct them:
Composition shines in situations where it's necessary to extend or override the functionality of the embedded type. Here, Person
has a GetUp()
method that is overridden for Student
.
Bravo! We've journeyed through Go's Composition, understanding key terms such as Embedding
and Anonymous Fields
and implementing Composition in Go code. Prepare for exercises that will reinforce your learning and build confidence in using Composition in Go!
