Search⌘ K

Composition with Structs

Explore how Go implements composition through struct embedding as an alternative to inheritance. Understand how to embed structs and methods, handle shadowing, and use slices of structs. This lesson helps you build loosely coupled software and apply dependency injection effectively.

Before we test complex scenarios, we have to learn more about structs and composition. These two concepts are mandatory to implement the dependency injection pattern and write loosely-coupled software.

Inheritance vs. composition

Go doesn’t support inheritance. Inheritance can be defined as a hierarchical relationship between parent and child classes. In practice, child classes inherit the fields, properties, and methods of parent classes. In Go, we don’t have classes, so this concept can’t be applied. Instead of classes, we have structs, and in place of inheritance, we have composition.
Let’s visualize the difference between these two terms:

Inheritance in OOP languages
Inheritance in OOP languages

The above pattern is pretty common in object-oriented programming (OOP). The Vehicle class is the ...