Lesson Overview

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.

Understanding Struct Buzzwords

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.

Working with Composition in Go: Part 1

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.

Working with Composition in Go: Part 2

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:

Power of Composition: Extending and Overriding

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.

Lesson Summary and Next Steps

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!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal