From the course: Treating Go as an Object-Oriented Language

Unlock the full course today

Join today to access over 24,900 courses taught by industry experts.

Composition

Composition

- [Instructor] We already talked about that Go doesn't support inheritance, but it does support composition. So let's talk about the details of composition itself. First of all, it's extremely easy to use. It allows you to share logic from one struct to another. In the same way, it allows you to share data. Now, this is very useful for common patterns that exist on multiple structs. For instance, I use this a lot when dealing with writing audit logic to my database tables. The audit fields are in a struct, and then that struct is composed into every data table representation. Therefore, I get shared behavior across multiple data table structs from the composed struct. Now it's time to talk a little bit about how to actually use it. You start by building a struct. You then include that struct in another struct as an attribute. It can be either named or unnamed. Methods of the struct appear as though they are on the…

Contents